file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.5.10; import 'openzeppelin-solidity/contracts/token/ERC20/ERC20.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import './Loans.sol'; import './Medianizer.sol'; import './DSMath.sol'; /** * @title Atomic Loans Sales Contract * @author Atomic Loans */ contract Sales is DSMath { FundsInterface funds; Loans loans; Medianizer med; uint256 public constant SWAP_EXP = 2 hours; // Swap Expiration uint256 public constant SETTLEMENT_EXP = 4 hours; // Settlement Expiration uint256 public constant MAX_NUM_LIQUIDATIONS = 3; // Maximum number of liquidations that can occur uint256 public constant MAX_UINT_256 = 2**256-1; address public deployer; // Only the Loans contract can edit data mapping (bytes32 => Sale) public sales; // Auctions mapping (bytes32 => Sig) public borrowerSigs; // Borrower Signatures mapping (bytes32 => Sig) public lenderSigs; // Lender Signatures mapping (bytes32 => Sig) public arbiterSigs; // Arbiter Signatures mapping (bytes32 => SecretHash) public secretHashes; // Auction Secret Hashes uint256 public saleIndex; // Auction Index mapping (bytes32 => bytes32[]) public saleIndexByLoan; // Loan Auctions (find by loanIndex) mapping(bytes32 => bool) revealed; ERC20 public token; /** * @notice Container for the sale information * @member loanIndex The Id of the loan * @member discountBuy The amount in tokens that the Bitcoin collateral was bought for at discount * @member liquidator The address of the liquidator (party that buys the Bitcoin collateral at a discount) * @member borrower The address of the borrower * @member lender The address of the lender * @member arbiter The address of the arbiter * @member createAt The creation timestamp of the sale * @member pubKeyHash The Bitcoin Public Key Hash of the liquidator * @member set Indicates that the sale at this specific index has been opened * @member accepted Indicates that the discountBuy has been accepted * @member off Indicates that the Sale is failed */ struct Sale { bytes32 loanIndex; uint256 discountBuy; address liquidator; address borrower; address lender; address arbiter; uint256 createdAt; bytes20 pubKeyHash; bool set; bool accepted; bool off; } /** * @notice Container for the Bitcoin refundable and seizable signature information * @member refundableSig The Bitcoin refundable signature to move collateral to swap P2WSH * @member seizableSig The Bitcoin seizable signature to move collateral to swap P2WSH */ struct Sig { bytes refundableSig; bytes seizableSig; } /** * @notice Container for the Bitcoin Secret and Secret Hashes information */ struct SecretHash { bytes32 secretHashA; // Secret Hash A bytes32 secretA; // Secret A bytes32 secretHashB; // Secret Hash B bytes32 secretB; // Secret B bytes32 secretHashC; // Secret Hash C bytes32 secretC; // Secret C bytes32 secretHashD; // Secret Hash D bytes32 secretD; // Secret D } event Create(bytes32 sale); event ProvideSig(bytes32 sale); event ProvideSecret(bytes32 sale, bytes32 secret_); event Accept(bytes32 sale); event Refund(bytes32 sale); /** * @notice Get Discount Buy price for a Sale * @param sale The Id of a Sale * @return Value of the Discount Buy price */ function discountBuy(bytes32 sale) external view returns (uint256) { return sales[sale].discountBuy; } /** * @notice Get the Swap Expiration of a Sale * @param sale The Id of a Sale * @return Swap Expiration Timestamp */ function swapExpiration(bytes32 sale) external view returns (uint256) { return sales[sale].createdAt + SWAP_EXP; } /** * @notice Get the Settlement Expiration of a Sale * @param sale The Id of a Sale * @return Settlement Expiration Timestamp */ function settlementExpiration(bytes32 sale) public view returns (uint256) { return sales[sale].createdAt + SETTLEMENT_EXP; } /** * @notice Get the accepted status of a Sale * @param sale The Id of a Sale * @return Bool that indicates whether Sale has been accepted */ function accepted(bytes32 sale) public view returns (bool) { return sales[sale].accepted; } /** * @notice Get the off status of a Sale * @param sale The Id of a Sale * @return Bool that indicates whether Sale has been terminated */ function off(bytes32 sale) public view returns (bool) { return sales[sale].off; } /** * @notice Construct a new Sales contract * @param loans_ The address of the Loans contract * @param funds_ The address of the Funds contract * @param med_ The address of the Medianizer contract * @param token_ The stablecoin token address */ constructor (Loans loans_, FundsInterface funds_, Medianizer med_, ERC20 token_) public { require(address(loans_) != address(0), "Loans address must be non-zero"); require(address(funds_) != address(0), "Funds address must be non-zero"); require(address(med_) != address(0), "Medianizer address must be non-zero"); require(address(token_) != address(0), "Token address must be non-zero"); deployer = address(loans_); loans = loans_; funds = funds_; med = med_; token = token_; require(token.approve(address(funds), MAX_UINT_256), "Token approve failed"); } /** * @notice Get the next Sale for a Loan * @param loan The Id of a Loan * @return Bool that indicates whether Sale has been terminated */ function next(bytes32 loan) public view returns (uint256) { return saleIndexByLoan[loan].length; } /** * @notice Creates a new sale (called by the Loans contract) * @param loanIndex The Id of the Loan * @param borrower The address of the borrower * @param lender The address of the lender * @param arbiter The address of the arbiter * @param liquidator The address of the liquidator * @param secretHashA The Secret Hash of the Borrower for the current sale number * @param secretHashB The Secret Hash of the Lender for the current sale number * @param secretHashC The Secret Hash of the Arbiter for the current sale number * @param secretHashD the Secret Hash of the Liquidator * @param pubKeyHash The Bitcoin Public Key Hash of the Liquidator * @return sale The Id of the sale */ function create( bytes32 loanIndex, address borrower, address lender, address arbiter, address liquidator, bytes32 secretHashA, bytes32 secretHashB, bytes32 secretHashC, bytes32 secretHashD, bytes20 pubKeyHash ) external returns(bytes32 sale) { require(msg.sender == address(loans), "Sales.create: Only the Loans contract can create a Sale"); saleIndex = add(saleIndex, 1); sale = bytes32(saleIndex); sales[sale].loanIndex = loanIndex; sales[sale].borrower = borrower; sales[sale].lender = lender; sales[sale].arbiter = arbiter; sales[sale].liquidator = liquidator; sales[sale].createdAt = now; sales[sale].pubKeyHash = pubKeyHash; sales[sale].discountBuy = loans.ddiv(loans.discountCollateralValue(loanIndex)); sales[sale].set = true; secretHashes[sale].secretHashA = secretHashA; secretHashes[sale].secretHashB = secretHashB; secretHashes[sale].secretHashC = secretHashC; secretHashes[sale].secretHashD = secretHashD; saleIndexByLoan[loanIndex].push(sale); emit Create(sale); } /** * @notice Provide Bitcoin signatures for moving collateral to collateral swap script * @param sale The Id of the sale * @param refundableSig The Bitcoin refundable collateral signature * @param seizableSig The Bitcoin seizable collateral signature * * Note: More info on the collateral swap script can be seen here: https://github.com/AtomicLoans/chainabstractionlayer-loans */ function provideSig( bytes32 sale, bytes calldata refundableSig, bytes calldata seizableSig ) external { require(sales[sale].set, "Sales.provideSig: Sale must be set"); require(now < settlementExpiration(sale), "Sales.provideSig: Cannot provide signature after settlement expiration"); require(BytesLib.toBytes32(refundableSig) != bytes32(0), "Sales.provideSig: refundableSig must be non-zero"); require(BytesLib.toBytes32(seizableSig) != bytes32(0), "Sales.provideSig: seizableSig must be non-zero"); if (msg.sender == sales[sale].borrower) { borrowerSigs[sale].refundableSig = refundableSig; borrowerSigs[sale].seizableSig = seizableSig; } else if (msg.sender == sales[sale].lender) { lenderSigs[sale].refundableSig = refundableSig; lenderSigs[sale].seizableSig = seizableSig; } else if (msg.sender == sales[sale].arbiter) { arbiterSigs[sale].refundableSig = refundableSig; arbiterSigs[sale].seizableSig = seizableSig; } else { revert("Loans.provideSig: Must be called by Borrower, Lender or Arbiter"); } emit ProvideSig(sale); } /** * @notice Provide secret to enable liquidator to claim collateral * @param secret_ The secret provided by the borrower, lender, arbiter, or liquidator */ function provideSecret(bytes32 sale, bytes32 secret_) public { require(sales[sale].set, "Sales.provideSecret: Sale must be set"); bytes32 secretHash = sha256(abi.encodePacked(secret_)); revealed[secretHash] = true; if (secretHash == secretHashes[sale].secretHashA) {secretHashes[sale].secretA = secret_;} if (secretHash == secretHashes[sale].secretHashB) {secretHashes[sale].secretB = secret_;} if (secretHash == secretHashes[sale].secretHashC) {secretHashes[sale].secretC = secret_;} if (secretHash == secretHashes[sale].secretHashD) {secretHashes[sale].secretD = secret_;} emit ProvideSecret(sale, secret_); } /** * @notice Indicates that two of Secret A, Secret B, Secret C have been submitted * @param sale The Id of the sale */ function hasSecrets(bytes32 sale) public view returns (bool) { uint8 numCorrectSecrets = 0; if (revealed[secretHashes[sale].secretHashA]) {numCorrectSecrets += 1;} if (revealed[secretHashes[sale].secretHashB]) {numCorrectSecrets += 1;} if (revealed[secretHashes[sale].secretHashC]) {numCorrectSecrets += 1;} return (numCorrectSecrets >= 2); } /** * @notice Accept discount buy by liquidator and disperse funds to rightful parties * @param sale The Id of the sale */ function accept(bytes32 sale) public { require(!accepted(sale), "Sales.accept: Sale must not already be accepted"); require(!off(sale), "Sales.accept: Sale must not already be off"); require(hasSecrets(sale), "Sales.accept: Secrets need to have already been revealed"); require(revealed[secretHashes[sale].secretHashD], "Sales.accept: Secret D must have already been revealed"); sales[sale].accepted = true; // First calculate available funds that can be dispursed uint256 available = add(sales[sale].discountBuy, loans.repaid(sales[sale].loanIndex)); // Use available funds to pay Arbiter fee if (sales[sale].arbiter != address(0) && available >= loans.fee(sales[sale].loanIndex)) { require(token.transfer(sales[sale].arbiter, loans.fee(sales[sale].loanIndex)), "Sales.accept: Token transfer of fee to Arbiter failed"); available = sub(available, loans.fee(sales[sale].loanIndex)); } // Determine amount remaining after removing owedToLender from available uint256 amount = min(available, loans.owedToLender(sales[sale].loanIndex)); // Transfer amount owedToLender to Lender or Deposit into their Fund if they have one if (loans.fundIndex(sales[sale].loanIndex) == bytes32(0)) { require(token.transfer(sales[sale].lender, amount), "Sales.accept: Token transfer of amount left to Lender failed"); } else { funds.deposit(loans.fundIndex(sales[sale].loanIndex), amount); } // Calculate available Funds after subtracting amount owed to Lender available = sub(available, amount); // Send penalty amount to oracles if there is enough available, else transfer remaining funds to oracles if (available >= loans.penalty(sales[sale].loanIndex)) { require(token.approve(address(med), loans.penalty(sales[sale].loanIndex)), "Sales.accept: Token transfer of penalty to Medianizer failed"); med.fund(loans.penalty(sales[sale].loanIndex), token); available = sub(available, loans.penalty(sales[sale].loanIndex)); } else if (available > 0) { require(token.approve(address(med), available), "Sales.accept: Token transfer of tokens available to Medianizer failed"); med.fund(available, token); available = 0; } // If there are still funds available after repaying all other parties, send the remaining funds to the Borrower if (available > 0) { require(token.transfer(sales[sale].borrower, available), "Sales.accept: Token transfer of tokens available to Borrower failed"); } emit Accept(sale); } /** * @notice Provide secrets to enable liquidator to claim collateral then accept discount buy to disperse funds to rightful parties * @param sale The Id of the sale * @param secrets_ The secrets provided by the borrower, lender, arbiter, or liquidator */ function provideSecretsAndAccept(bytes32 sale, bytes32[3] calldata secrets_) external { provideSecret(sale, secrets_[0]); provideSecret(sale, secrets_[1]); provideSecret(sale, secrets_[2]); accept(sale); } /** * @notice Refund discount buy to liquidator * @param sale The Id of the sale */ function refund(bytes32 sale) external { require(!accepted(sale), "Sales.refund: Sale must not be accepted"); require(!off(sale), "Sales.refund: Sale must not be off"); require(now > settlementExpiration(sale), "Sales.refund: Can only refund after settlement expiration"); require(sales[sale].discountBuy > 0, "Sales.refund: Discount Buy amount must be non-zero"); sales[sale].off = true; require(token.transfer(sales[sale].liquidator, sales[sale].discountBuy), "Sales.refund: Token transfer to Liquidator failed"); if (next(sales[sale].loanIndex) == MAX_NUM_LIQUIDATIONS) { require(token.transfer(sales[sale].borrower, loans.repaid(sales[sale].loanIndex)), "Sales.refund: Token transfer to Borrower failed"); } emit Refund(sale); } }
* @notice Container for the Bitcoin refundable and seizable signature information @member refundableSig The Bitcoin refundable signature to move collateral to swap P2WSH @member seizableSig The Bitcoin seizable signature to move collateral to swap P2WSH/
struct Sig { bytes refundableSig; bytes seizableSig; }
1,065,989
[ 1, 2170, 364, 326, 24420, 16255, 429, 471, 695, 6934, 3372, 1779, 632, 5990, 16255, 429, 8267, 1021, 24420, 16255, 429, 3372, 358, 3635, 4508, 2045, 287, 358, 7720, 453, 22, 2651, 44, 632, 5990, 695, 6934, 8267, 1021, 24420, 695, 6934, 3372, 358, 3635, 4508, 2045, 287, 358, 7720, 453, 22, 2651, 44, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 21911, 288, 203, 3639, 1731, 16255, 429, 8267, 31, 203, 3639, 1731, 695, 6934, 8267, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: zeppelin-solidity/contracts/lifecycle/Destructible.sol /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { constructor() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/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: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/token/ERC223/ERC223Basic.sol /** * @title ERC223Basic extends ERC20 interface and supports ERC223 */ contract ERC223Basic is ERC20Basic { function transfer(address _to, uint256 _value, bytes _data) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // File: contracts/token/ERC223/ERC223ReceivingContract.sol /** * @title ERC223ReceivingContract contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) public returns (bool); } // File: contracts/Adminable.sol /** * @title Adminable * @dev The Adminable contract has the simple protection logic, and provides admin based access control */ contract Adminable is Ownable { address public admin; event AdminDesignated(address indexed previousAdmin, address indexed newAdmin); /** * @dev Throws if called the non admin. */ modifier onlyAdmin() { require(msg.sender == admin); _; } /** * @dev Throws if called the non owner and non admin. */ modifier onlyOwnerOrAdmin() { require(msg.sender == owner || msg.sender == admin); _; } /** * @dev Designate new admin for the address * @param _address address The address you want to be a new admin */ function designateAdmin(address _address) public onlyOwner { require(_address != address(0) && _address != owner); emit AdminDesignated(admin, _address); admin = _address; } } // File: contracts/Lockable.sol /** * @title Lockable * @dev The Lockable contract has an locks address map, and provides lockable control * functions, this simplifies the implementation of "lock transfers". * * The contents of this Smart Contract and all associated code is owned and operated by Rubiix, a Gibraltar company in formation. */ contract Lockable is Adminable, ERC20Basic { using SafeMath for uint256; // EPOCH TIMESTAMP OF "Tue Jul 02 2019 00:00:00 GMT+0000" // @see https://www.unixtimestamp.com/index.php uint public globalUnlockTime = 1562025600; uint public constant decimals = 18; event UnLock(address indexed unlocked); event Lock(address indexed locked, uint until, uint256 value, uint count); event UpdateGlobalUnlockTime(uint256 epoch); struct LockMeta { uint256 value; uint until; } mapping(address => LockMeta[]) internal locksMeta; mapping(address => bool) locks; /** * @dev Lock tokens for the address * @param _address address The address you want to lock tokens * @param _days uint The days count you want to lock untill from now * @param _value uint256 the amount of tokens to be locked */ function lock(address _address, uint _days, uint256 _value) onlyOwnerOrAdmin public { _value = _value*(10**decimals); require(_value > 0); require(_days > 0); require(_address != owner); require(_address != admin); uint untilTime = block.timestamp + _days * 1 days; locks[_address] = true; // check if we have locks locksMeta[_address].push(LockMeta(_value, untilTime)); // fire lock event emit Lock(_address, untilTime, _value, locksMeta[_address].length); } /** * @dev Unlock tokens for the address * @param _address address The address you want to unlock tokens */ function unlock(address _address) onlyOwnerOrAdmin public { locks[_address] = false; delete locksMeta[_address]; emit UnLock(_address); } /** * @dev Gets the locked balance of the specified address and time * @param _owner The address to query the locked balance of. * @param _time The timestamp seconds to query the locked balance of. * @return An uint256 representing the locked amount owned by the passed address. */ function lockedBalanceOf(address _owner, uint _time) public view returns (uint256) { LockMeta[] memory locked = locksMeta[_owner]; uint length = locked.length; // if no locks or even not created (takes bdefault) return 0 if (length == 0) { return 0; } // sum all available locks uint256 _result = 0; for (uint i = 0; i < length; i++) { if (_time <= locked[i].until) { _result = _result.add(locked[i].value); } } return _result; } /** * @dev Gets the locked balance of the specified address of the current time * @param _owner The address to query the locked balance of. * @return An uint256 representing the locked amount owned by the passed address. */ function lockedNowBalanceOf(address _owner) public view returns (uint256) { return this.lockedBalanceOf(_owner, block.timestamp); } /** * @dev Gets the unlocked balance of the specified address and time * @param _owner The address to query the unlocked balance of. * @param _time The timestamp seconds to query the unlocked balance of. * @return An uint256 representing the unlocked amount owned by the passed address. */ function unlockedBalanceOf(address _owner, uint _time) public view returns (uint256) { return this.balanceOf(_owner).sub(lockedBalanceOf(_owner, _time)); } /** * @dev Gets the unlocked balance of the specified address of the current time * @param _owner The address to query the unlocked balance of. * @return An uint256 representing the unlocked amount owned by the passed address. */ function unlockedNowBalanceOf(address _owner) public view returns (uint256) { return this.unlockedBalanceOf(_owner, block.timestamp); } function updateGlobalUnlockTime(uint256 _epoch) public onlyOwnerOrAdmin returns (bool) { require(_epoch >= 0); globalUnlockTime = _epoch; emit UpdateGlobalUnlockTime(_epoch); // Gives owner the ability to update lockup period for all wallets. // Owner can pass an epoch timecode into the function to: // 1. Extend lockup period, // 2. Unlock all wallets by passing '0' into the function } /** * @dev Throws if the value less than the current unlocked balance of. */ modifier onlyUnlocked(uint256 _value) { if(block.timestamp > globalUnlockTime) { _; } else { if (locks[msg.sender] == true) { require(this.unlockedNowBalanceOf(msg.sender) >= _value); } _; } } /** * @dev Throws if the value less than the current unlocked balance of the given address. */ modifier onlyUnlockedOf(address _address, uint256 _value) { if(block.timestamp > globalUnlockTime) { _; } else { if (locks[_address] == true) { require(this.unlockedNowBalanceOf(_address) >= _value); } else { } _; } } } // File: contracts/StandardLockableToken.sol /** * @title StandardLockableToken * * The contents of this Smart Contract and all associated code is owned and operated by Rubiix, a Gibraltar company in formation. */ contract StandardLockableToken is Lockable, /**/ERC223Basic, /*ERC20*/StandardToken { /** * @dev Check address is to be a contract based on extcodesize (must be nonzero to be a contract) * @param _address The address to check. */ function isContract(address _address) private constant returns (bool) { uint256 codeLength; assembly { codeLength := extcodesize(_address) } return codeLength > 0; } /** * @dev Transfer token for a specified address * ERC20 support * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) onlyUnlocked(_value) public returns (bool) { bytes memory empty; return _transfer(_to, _value, empty); } /** * @dev Transfer token for a specified address * ERC223 support * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The additional data. */ function transfer(address _to, uint256 _value, bytes _data) onlyUnlocked(_value) public returns (bool) { return _transfer(_to, _value, _data); } /** * @dev Transfer token for a specified address * ERC223 support * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The additional data. */ function _transfer(address _to, uint256 _value, bytes _data) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value > 0); // catch overflow loosing tokens // require(balances[_to] + _value > balances[_to]); // safety update balances balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); // determine if the contract given if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } // emit ERC20 transfer event emit Transfer(msg.sender, _to, _value); // emit ERC223 transfer event emit Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) onlyUnlockedOf(_from, _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_value > 0); // make balances manipulations first balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); bytes memory empty; if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } // emit ERC20 transfer event emit Transfer(_from, _to, _value); // emit ERC223 transfer event emit Transfer(_from, _to, _value, empty); return true; } } // File: contracts/StandardBurnableLockableToken.sol /** * @title StandardBurnableLockableToken * * The contents of this Smart Contract and all associated code is owned and operated by Rubiix, a Gibraltar company in formation. */ contract StandardBurnableLockableToken is StandardLockableToken, BurnableToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) onlyOwner onlyUnlockedOf(_from, _value) public { require(_value <= allowed[_from][msg.sender]); require(_value > 0); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); bytes memory empty; // emit ERC223 transfer event also emit Transfer(msg.sender, address(0), _value, empty); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) onlyOwner onlyUnlocked(_value) public { require(_value > 0); _burn(msg.sender, _value); bytes memory empty; // emit ERC223 transfer event also emit Transfer(msg.sender, address(0), _value, empty); } } // File: contracts/RubiixToken.sol /** * @title RubiixToken * @dev The RubiixToken contract is an Standard ERC20 and ERC223 Lockable smart contract * uses as a coin * * The contents of this Smart Contract and all associated code is owned and operated by Rubiix, a Gibraltar company in formation. */ contract RubiixToken is StandardBurnableLockableToken, Destructible { string public constant name = "Rubiix Token"; uint public constant decimals = 18; string public constant symbol = "RBX"; /** * @dev Inits an owner, totalSupply and assigns tokens for the reserved addresses. * Owner = 55% * Team = 20% * Company = 23% * Wallet = 2% * Fires ERC20 & ERC223 transfer events */ constructor() public { // set the owner owner = msg.sender; admin = 0xfb36E83F6bE7C0E9ba9FF403389001f2312121aF; uint256 INITIAL_SUPPLY = 223684211 * (10**decimals); // init totalSupply totalSupply_ = INITIAL_SUPPLY; // TODO: use info instead of empty. for example: team reserved bytes memory empty; // Owner = 55% uint256 ownerSupply = 12302631605 * (10**(decimals-2)); balances[msg.sender] = ownerSupply; emit Transfer(address(0), msg.sender, ownerSupply); emit Transfer(address(0), msg.sender, ownerSupply, empty); // Team = 20% address teamAddress = 0x7B1Af4A3b427C8eED8aA36a9f997b056853d0e36; uint256 teamSupply = 447368422 * (10**(decimals - 1)); balances[teamAddress] = teamSupply; emit Transfer(address(0), teamAddress, teamSupply); emit Transfer(address(0), teamAddress, teamSupply, empty); // Company = 23% address companyAddress = 0x3AFb62d009fEe4DD66A405f191B25e77f1d64126; uint256 companySupply = 5144736853 * (10**(decimals-2)); balances[companyAddress] = companySupply; emit Transfer(address(0), companyAddress, companySupply); emit Transfer(address(0), companyAddress, companySupply, empty); // Wallet = 2% address walletAddress = 0x4E44743330b950a8c624C457178AaC1355c4f6b2; uint256 walletSupply = 447368422 * (10**(decimals-2)); balances[walletAddress] = walletSupply; emit Transfer(address(0), walletAddress, walletSupply); emit Transfer(address(0), walletAddress, walletSupply, empty); } }
* @dev Inits an owner, totalSupply and assigns tokens for the reserved addresses. Owner = 55% Team = 20% Company = 23% Wallet = 2% Fires ERC20 & ERC223 transfer events/ set the owner init totalSupply TODO: use info instead of empty. for example: team reserved Owner = 55% Team = 20% Company = 23% Wallet = 2%
constructor() public { owner = msg.sender; admin = 0xfb36E83F6bE7C0E9ba9FF403389001f2312121aF; uint256 INITIAL_SUPPLY = 223684211 * (10**decimals); totalSupply_ = INITIAL_SUPPLY; bytes memory empty; uint256 ownerSupply = 12302631605 * (10**(decimals-2)); balances[msg.sender] = ownerSupply; emit Transfer(address(0), msg.sender, ownerSupply); emit Transfer(address(0), msg.sender, ownerSupply, empty); address teamAddress = 0x7B1Af4A3b427C8eED8aA36a9f997b056853d0e36; uint256 teamSupply = 447368422 * (10**(decimals - 1)); balances[teamAddress] = teamSupply; emit Transfer(address(0), teamAddress, teamSupply); emit Transfer(address(0), teamAddress, teamSupply, empty); address companyAddress = 0x3AFb62d009fEe4DD66A405f191B25e77f1d64126; uint256 companySupply = 5144736853 * (10**(decimals-2)); balances[companyAddress] = companySupply; emit Transfer(address(0), companyAddress, companySupply); emit Transfer(address(0), companyAddress, companySupply, empty); address walletAddress = 0x4E44743330b950a8c624C457178AaC1355c4f6b2; uint256 walletSupply = 447368422 * (10**(decimals-2)); balances[walletAddress] = walletSupply; emit Transfer(address(0), walletAddress, walletSupply); emit Transfer(address(0), walletAddress, walletSupply, empty); }
14,086,569
[ 1, 382, 1282, 392, 3410, 16, 2078, 3088, 1283, 471, 22698, 2430, 364, 326, 8735, 6138, 18, 16837, 273, 21483, 9, 10434, 273, 4200, 9, 26782, 273, 10213, 9, 20126, 273, 576, 9, 478, 2814, 4232, 39, 3462, 473, 4232, 39, 3787, 23, 7412, 2641, 19, 444, 326, 3410, 1208, 2078, 3088, 1283, 2660, 30, 999, 1123, 3560, 434, 1008, 18, 364, 3454, 30, 5927, 8735, 16837, 273, 21483, 9, 10434, 273, 4200, 9, 26782, 273, 10213, 9, 20126, 273, 576, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 3885, 1435, 1071, 288, 203, 565, 3410, 273, 1234, 18, 15330, 31, 203, 565, 3981, 273, 374, 5841, 70, 5718, 41, 10261, 42, 26, 70, 41, 27, 39, 20, 41, 29, 12124, 29, 2246, 7132, 3707, 6675, 11664, 74, 4366, 2138, 26009, 69, 42, 31, 203, 203, 565, 2254, 5034, 28226, 67, 13272, 23893, 273, 576, 29941, 5193, 22, 2499, 380, 261, 2163, 636, 31734, 1769, 203, 203, 565, 2078, 3088, 1283, 67, 273, 28226, 67, 13272, 23893, 31, 203, 203, 565, 1731, 3778, 1008, 31, 203, 203, 565, 2254, 5034, 3410, 3088, 1283, 273, 225, 17335, 3103, 4449, 2313, 6260, 380, 261, 2163, 636, 12, 31734, 17, 22, 10019, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 3410, 3088, 1283, 31, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 3410, 3088, 1283, 1769, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 3410, 3088, 1283, 16, 1008, 1769, 203, 203, 565, 1758, 5927, 1887, 273, 374, 92, 27, 38, 21, 12664, 24, 37, 23, 70, 24, 5324, 39, 28, 73, 2056, 28, 69, 37, 5718, 69, 29, 74, 2733, 27, 70, 20, 4313, 7140, 23, 72, 20, 73, 5718, 31, 203, 565, 2254, 5034, 5927, 3088, 1283, 273, 1059, 9462, 5718, 5193, 3787, 380, 261, 2163, 636, 12, 31734, 300, 404, 10019, 203, 565, 324, 26488, 63, 10035, 1887, 65, 273, 5927, 3088, 1283, 31, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 5927, 1887, 16, 5927, 3088, 1283, 1769, 2 ]
./partial_match/1/0x93A20D8EbA6997ABB53aE94bd01727C8e74c8734/sources/TokenCore.sol
* @dev toUint256/ solhint-disable-next-line no-inline-assembly
function toUint256(bytes memory _source) internal pure returns (uint256 result) { require(_source.length == 32, "BC01"); assembly { result := mload(add(_source, 0x20)) } }
3,566,153
[ 1, 869, 5487, 5034, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 358, 5487, 5034, 12, 3890, 3778, 389, 3168, 13, 2713, 16618, 1135, 261, 11890, 5034, 563, 13, 288, 203, 565, 2583, 24899, 3168, 18, 2469, 422, 3847, 16, 315, 16283, 1611, 8863, 203, 565, 19931, 288, 203, 1377, 563, 519, 312, 945, 12, 1289, 24899, 3168, 16, 374, 92, 3462, 3719, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.8.4; import "@prb/contracts/token/erc20/IErc20.sol"; import "@prb/contracts/access/IOwnable.sol"; import "../external/chainlink/IAggregatorV3.sol"; /// @title IChainlinkOperator /// @author Hifi /// @notice Aggregates the price feeds provided by Chainlink. interface IChainlinkOperator { /// CUSTOM ERRORS /// /// @notice Emitted when the decimal precision of the feed is not the same as the expected number. error ChainlinkOperator__DecimalsMismatch(string symbol, uint256 decimals); /// @notice Emitted when trying to interact with a feed not set yet. error ChainlinkOperator__FeedNotSet(string symbol); /// @notice Emitted when the price returned by the oracle is zero. error ChainlinkOperator__PriceZero(string symbol); /// EVENTS /// /// @notice Emitted when a feed is deleted. /// @param asset The related asset. /// @param feed The related feed. event DeleteFeed(IErc20 indexed asset, IAggregatorV3 indexed feed); /// @notice Emitted when a feed is set. /// @param asset The related asset. /// @param feed The related feed. event SetFeed(IErc20 indexed asset, IAggregatorV3 indexed feed); /// STRUCTS /// struct Feed { IErc20 asset; IAggregatorV3 id; bool isSet; } /// CONSTANT FUNCTIONS /// /// @notice Gets the official feed for a symbol. /// @param symbol The symbol to return the feed for. /// @return (address asset, address id, bool isSet). function getFeed(string memory symbol) external view returns ( IErc20, IAggregatorV3, bool ); /// @notice Gets the official price for a symbol and adjusts it have 18 decimals instead of the /// format used by Chainlink, which has 8 decimals. /// /// @dev Requirements: /// - The normalized price cannot overflow. /// /// @param symbol The Erc20 symbol of the token for which to query the price. /// @return The normalized price. function getNormalizedPrice(string memory symbol) external view returns (uint256); /// @notice Gets the official price for a symbol in the default format used by Chainlink, which /// has 8 decimals. /// /// @dev Requirements: /// /// - The feed must be set. /// - The price returned by the oracle cannot be zero. /// /// @param symbol The symbol to fetch the price for. /// @return The price denominated in USD, with 8 decimals. function getPrice(string memory symbol) external view returns (uint256); /// @notice Chainlink price precision for USD-quoted data. function pricePrecision() external view returns (uint256); /// @notice The ratio between normalized precision (1e18) and the Chainlink price precision (1e8). function pricePrecisionScalar() external view returns (uint256); /// NON-CONSTANT FUNCTIONS /// /// @notice Deletes a previously set Chainlink price feed. /// /// @dev Emits a {DeleteFeed} event. /// /// Requirements: /// /// - The caller must be the owner. /// - The feed must be set already. /// /// @param symbol The Erc20 symbol of the asset to delete the feed for. function deleteFeed(string memory symbol) external; /// @notice Sets a Chainlink price feed. /// /// @dev It is not an error to set a feed twice. Emits a {SetFeed} event. /// /// Requirements: /// /// - The caller must be the owner. /// - The number of decimals of the feed must be 8. /// /// @param asset The address of the Erc20 contract for which to get the price. /// @param feed The address of the Chainlink price feed contract. function setFeed(IErc20 asset, IAggregatorV3 feed) external; }
@title IChainlinkOperator @author Hifi @notice Aggregates the price feeds provided by Chainlink.
interface IChainlinkOperator { error ChainlinkOperator__DecimalsMismatch(string symbol, uint256 decimals); error ChainlinkOperator__FeedNotSet(string symbol); error ChainlinkOperator__PriceZero(string symbol); event DeleteFeed(IErc20 indexed asset, IAggregatorV3 indexed feed); event SetFeed(IErc20 indexed asset, IAggregatorV3 indexed feed); pragma solidity >=0.8.4; struct Feed { IErc20 asset; IAggregatorV3 id; bool isSet; } }
13,140,759
[ 1, 45, 3893, 1232, 5592, 225, 670, 704, 225, 10594, 815, 326, 6205, 27684, 2112, 635, 7824, 1232, 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 ]
[ 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, 5831, 467, 3893, 1232, 5592, 288, 203, 203, 565, 555, 7824, 1232, 5592, 972, 31809, 16901, 12, 1080, 3273, 16, 2254, 5034, 15105, 1769, 203, 203, 565, 555, 7824, 1232, 5592, 972, 8141, 1248, 694, 12, 1080, 3273, 1769, 203, 203, 565, 555, 7824, 1232, 5592, 972, 5147, 7170, 12, 1080, 3273, 1769, 203, 203, 203, 565, 871, 2504, 8141, 12, 8732, 1310, 3462, 8808, 3310, 16, 467, 17711, 58, 23, 8808, 4746, 1769, 203, 203, 565, 871, 1000, 8141, 12, 8732, 1310, 3462, 8808, 3310, 16, 467, 17711, 58, 23, 8808, 4746, 1769, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 14013, 288, 203, 3639, 10897, 1310, 3462, 3310, 31, 203, 3639, 467, 17711, 58, 23, 612, 31, 203, 3639, 1426, 13532, 31, 203, 565, 289, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8fBeDAFCc0a4EDA503ceEd3FF64e668AB27B4D65/sources/xBRKB.sol
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the account that deploys the contract. See {ERC20-constructor}./Mint amount to the sender
constructor(string memory contractName, string memory contractSymbol, uint256 initialAmount, uint8 decimals) ERC20(contractName, contractSymbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupDecimals(decimals); _mint(_msgSender(), initialAmount * (10 ** uint256(decimals))); }
2,604,112
[ 1, 29598, 1375, 5280, 67, 15468, 67, 16256, 9191, 1375, 6236, 2560, 67, 16256, 9191, 1375, 4066, 4714, 67, 16256, 68, 358, 326, 2236, 716, 5993, 383, 1900, 326, 6835, 18, 2164, 288, 654, 39, 3462, 17, 12316, 5496, 19, 49, 474, 3844, 358, 326, 5793, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 1080, 3778, 6835, 461, 16, 533, 3778, 6835, 5335, 16, 2254, 5034, 2172, 6275, 16, 2254, 28, 15105, 13, 4232, 39, 3462, 12, 16351, 461, 16, 6835, 5335, 13, 288, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 31809, 12, 31734, 1769, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2172, 6275, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 3719, 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 ]
./full_match/1/0x3499933f1808B1b43Bfc126359c25e2592Ea8bd8/sources/contracts/Airdrop.sol
* Notify metadata changed*/
event MetadataChanges(uint256 indexed _id, string _value, address indexed caller);
2,987,667
[ 1, 9168, 1982, 3550, 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, 565, 871, 6912, 7173, 12, 11890, 5034, 8808, 389, 350, 16, 533, 389, 1132, 16, 1758, 8808, 4894, 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 ]
./full_match/3/0x30F06feCeFB1DAd39bB850A9D8a3Bf1E53EF0136/sources/browser/ERC20_Gen_Lib.sol
---------------------------------------------------------------------------- Owned contract ----------------------------------------------------------------------------
contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor(address p_owner) public { owner = p_owner; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } }
8,152,548
[ 1, 5802, 7620, 14223, 11748, 6835, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 11748, 288, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 394, 5541, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 1769, 203, 203, 565, 3885, 12, 2867, 293, 67, 8443, 13, 1071, 288, 203, 3639, 3410, 273, 293, 67, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 389, 2704, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 394, 5541, 273, 389, 2704, 5541, 31, 203, 565, 289, 203, 565, 445, 2791, 5460, 12565, 1435, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 394, 5541, 1769, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 8443, 16, 394, 5541, 1769, 203, 3639, 3410, 273, 394, 5541, 31, 203, 3639, 394, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 "../helpers/LiquityHelper.sol"; import "../../../utils/TokenUtils.sol"; import "../../ActionBase.sol"; contract LiquityOpen is ActionBase, LiquityHelper { using TokenUtils for address; struct Params { uint256 maxFeePercentage; // Highest borrowing fee to accept, ranges between 0.5 and 5% uint256 collAmount; // Amount of WETH tokens to supply as collateral uint256 lusdAmount; // Amount of LUSD tokens to borrow from the trove, protocol minimum net debt is 1800 address from; // Address where to pull the collateral from address to; // Address that will receive the borrowed tokens address upperHint; address lowerHint; } /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory params = parseInputs(_callData); params.maxFeePercentage = _parseParamUint( params.maxFeePercentage, _paramMapping[0], _subData, _returnValues ); params.collAmount = _parseParamUint( params.collAmount, _paramMapping[1], _subData, _returnValues ); params.lusdAmount = _parseParamUint( params.lusdAmount, _paramMapping[2], _subData, _returnValues ); params.from = _parseParamAddr(params.from, _paramMapping[3], _subData, _returnValues); params.to = _parseParamAddr(params.to, _paramMapping[4], _subData, _returnValues); uint256 troveOwner = _liquityOpen(params); return bytes32(troveOwner); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable virtual override { Params memory params = parseInputs(_callData); _liquityOpen(params); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Opens up a trove function _liquityOpen(Params memory _params) internal returns (uint256) { if (_params.collAmount == type(uint256).max) { _params.collAmount = TokenUtils.WETH_ADDR.getBalance(_params.from); } TokenUtils.WETH_ADDR.pullTokensIfNeeded(_params.from, _params.collAmount); TokenUtils.withdrawWeth(_params.collAmount); BorrowerOperations.openTrove{value: _params.collAmount}( _params.maxFeePercentage, _params.lusdAmount, _params.upperHint, _params.lowerHint ); LUSDTokenAddr.withdrawTokens(_params.to, _params.lusdAmount); logger.Log( address(this), msg.sender, "LiquityOpen", abi.encode( _params.maxFeePercentage, _params.collAmount, _params.lusdAmount, _params.from, _params.to ) ); return _params.collAmount; } function parseInputs(bytes[] memory _callData) internal pure returns (Params memory params) { params = abi.decode(_callData[0], (Params)); } }
Address where to pull the collateral from
address from;
5,390,605
[ 1, 1887, 1625, 358, 6892, 326, 4508, 2045, 287, 628, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1758, 628, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; // KingToken with Governance. contract LeToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name = "Legasys Token"; string private _symbol = "LeToken"; uint8 private _decimals = 18; /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Archbishop). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "LEGASYS::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "LEGASYS::delegateBySig: invalid nonce"); require(now <= expiry, "LEGASYS::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "LEGASYS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying KINGs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "LEGASYS::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "LEGASYS::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
240,197
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 19384, 3033, 61, 55, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2 ]
pragma solidity 0.5.17; /* import "./iElasticTokenInterface.sol"; */ import "./iTokenGovernance.sol"; import "../lib/SafeERC20.sol"; contract iElasticToken is iTokenGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyBanker() { require(msg.sender == banker); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov || msg.sender == banker, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(itokensScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * itokensScalingFactor // this is used to check if itokensScalingFactor will be too high to compute balances when rebasing. return uint256(- 1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply totalSupply = totalSupply.add(amount); // get underlying value uint256 itokenValue = _fragmentToiToken(amount); // increase initSupply initSupply = initSupply.add(itokenValue); // make sure the mint didnt push maxScalingFactor too low require(itokensScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _itokenBalances[to] = _itokenBalances[to].add(itokenValue); // add delegates to the minter _moveDelegates(address(0), _delegates[to], itokenValue); emit Mint(to, amount); emit Transfer(address(0), to, amount); } function burn(uint256 amount) external returns (bool) { _burn(msg.sender, amount); return true; } /// @notice Burns `_amount` token in `account`. Must only be called by the IFABank. function burnFrom(address account, uint256 amount) external onlyBanker returns (bool) { // decreased Allowance uint256 allowance = _allowedFragments[account][msg.sender]; uint256 decreasedAllowance = allowance.sub(amount); // approve _allowedFragments[account][msg.sender] = decreasedAllowance; emit Approval(account, msg.sender, decreasedAllowance); // burn _burn(account, amount); return true; } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); // get underlying value uint256 itokenValue = _fragmentToiToken(amount); // sub balance _itokenBalances[account] = _itokenBalances[account].sub(itokenValue); // decrease initSupply initSupply = initSupply.sub(itokenValue); // decrease totalSupply totalSupply = totalSupply.sub(amount); //remove delegates from the account _moveDelegates(_delegates[account], address(0), itokenValue); emit Burn(account, amount); emit Transfer(account, address(0), amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in itokens, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == itokensScalingFactor / 1e24; // get amount in underlying uint256 itokenValue = _fragmentToiToken(value); // sub from balance of sender _itokenBalances[msg.sender] = _itokenBalances[msg.sender].sub(itokenValue); // add to balance of receiver _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], itokenValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // get value in itokens uint256 itokenValue = _fragmentToiToken(value); // sub from from _itokenBalances[from] = _itokenBalances[from].sub(itokenValue); _itokenBalances[to] = _itokenBalances[to].add(itokenValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], itokenValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _itokenToFragment(_itokenBalances[who]); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _itokenBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } // --- Approve by signature --- function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(now <= deadline, "iToken/permit-expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); require(owner != address(0), "iToken/invalid-address-0"); require(owner == ecrecover(digest, v, r, s), "iToken/invalid-permit"); _allowedFragments[owner][spender] = value; emit Approval(owner, spender, value); } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the rebaser contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the banker * @param banker_ The address of the IFABank contract to use for authentication. */ function _setBanker(address banker_) external onlyGov { address oldBanker = banker; banker = banker_; emit NewBanker(oldBanker, banker_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { // no change if (indexDelta == 0) { emit Rebase(epoch, itokensScalingFactor, itokensScalingFactor); return totalSupply; } // for events uint256 previTokensScalingFactor = itokensScalingFactor; if (!positive) { // negative rebase, decrease scaling factor itokensScalingFactor = itokensScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { // positive reabse, increase scaling factor uint256 newScalingFactor = itokensScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { itokensScalingFactor = newScalingFactor; } else { itokensScalingFactor = _maxScalingFactor(); } } // update total supply, correctly totalSupply = _itokenToFragment(initSupply); emit Rebase(epoch, previTokensScalingFactor, itokensScalingFactor); return totalSupply; } function itokenToFragment(uint256 itoken) external view returns (uint256) { return _itokenToFragment(itoken); } function fragmentToiToken(uint256 value) external view returns (uint256) { return _fragmentToiToken(value); } function _itokenToFragment(uint256 itoken) internal view returns (uint256) { return itoken.mul(itokensScalingFactor).div(internalDecimals); } function _fragmentToiToken(uint256 value) internal view returns (uint256) { return value.mul(internalDecimals).div(itokensScalingFactor); } // Rescue tokens function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool) { // transfer to SafeERC20.safeTransfer(IERC20(token), to, amount); return true; } } contract iToken is iElasticToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initTotalSupply_ ) public { super.initialize(name_, symbol_, decimals_); itokensScalingFactor = BASE; initSupply = _fragmentToiToken(initTotalSupply_); totalSupply = initTotalSupply_; _itokenBalances[initial_owner] = initSupply; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); } }
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. This method is included for ERC20 compatibility. increaseAllowance and decreaseAllowance should be used instead. Changing an allowance with this method brings the risk that someone may transfer both the old and the new allowance - if they are both greater than zero - if a transfer transaction is mined before the later approve() call is mined. @param spender The address which will spend the funds. @param value The amount of tokens to be spent./
function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
6,403,358
[ 1, 12053, 537, 326, 2275, 1758, 358, 17571, 326, 1269, 3844, 434, 2430, 603, 12433, 6186, 434, 1234, 18, 15330, 18, 1220, 707, 353, 5849, 364, 4232, 39, 3462, 8926, 18, 10929, 7009, 1359, 471, 20467, 7009, 1359, 1410, 506, 1399, 3560, 18, 1680, 18183, 392, 1699, 1359, 598, 333, 707, 5186, 899, 326, 18404, 716, 18626, 2026, 7412, 3937, 326, 1592, 471, 326, 394, 1699, 1359, 300, 309, 2898, 854, 3937, 6802, 2353, 3634, 300, 309, 279, 7412, 2492, 353, 1131, 329, 1865, 326, 5137, 6617, 537, 1435, 745, 353, 1131, 329, 18, 225, 17571, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 460, 1021, 3844, 434, 2430, 358, 506, 26515, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 203, 565, 3903, 203, 565, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 389, 8151, 27588, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 3639, 3626, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x0f6029ebde2ecd9ab4d60dd5d0a297e9e59bf77a //Contract name: ADXExchange //Balance: 0 Ether //Verification Date: 11/16/2017 //Transacion Count: 34 // CODE STARTS HERE pragma solidity ^0.4.15; /** * @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; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract Drainable is Ownable { function withdrawToken(address tokenaddr) onlyOwner { ERC20 token = ERC20(tokenaddr); uint bal = token.balanceOf(address(this)); token.transfer(msg.sender, bal); } function withdrawEther() onlyOwner { require(msg.sender.send(this.balance)); } } contract ADXRegistry is Ownable, Drainable { string public name = "AdEx Registry"; // Structure: // AdUnit (advertiser) - a unit of a single advertisement // AdSlot (publisher) - a particular property (slot) that can display an ad unit // Campaign (advertiser) - group of ad units ; not vital // Channel (publisher) - group of properties ; not vital // Each Account is linked to all the items they own through the Account struct mapping (address => Account) public accounts; // XXX: mostly unused, because solidity does not allow mapping with enum as primary type.. :( we just use uint enum ItemType { AdUnit, AdSlot, Campaign, Channel } // uint here corresponds to the ItemType mapping (uint => uint) public counts; mapping (uint => mapping (uint => Item)) public items; // Publisher or Advertiser (could be both) struct Account { address addr; address wallet; bytes32 ipfs; // ipfs addr for additional (larger) meta bytes32 name; // name bytes32 meta; // metadata, can be JSON, can be other format, depends on the high-level implementation bytes32 signature; // signature in the off-blockchain state channel // Items, by type, then in an array of numeric IDs mapping (uint => uint[]) items; } // Sub-item, such as AdUnit, AdSlot, Campaign, Channel struct Item { uint id; address owner; ItemType itemType; bytes32 ipfs; // ipfs addr for additional (larger) meta bytes32 name; // name bytes32 meta; // metadata, can be JSON, can be other format, depends on the high-level implementation } modifier onlyRegistered() { var acc = accounts[msg.sender]; require(acc.addr != 0); _; } // can be called over and over to update the data // XXX consider entrance barrier, such as locking in some ADX function register(bytes32 _name, address _wallet, bytes32 _ipfs, bytes32 _sig, bytes32 _meta) external { require(_wallet != 0); // XXX should we ensure _sig is not 0? if so, also add test require(_name != 0); var isNew = accounts[msg.sender].addr == 0; var acc = accounts[msg.sender]; if (!isNew) require(acc.signature == _sig); else acc.signature = _sig; acc.addr = msg.sender; acc.wallet = _wallet; acc.ipfs = _ipfs; acc.name = _name; acc.meta = _meta; if (isNew) LogAccountRegistered(acc.addr, acc.wallet, acc.ipfs, acc.name, acc.meta, acc.signature); else LogAccountModified(acc.addr, acc.wallet, acc.ipfs, acc.name, acc.meta, acc.signature); } // use _id = 0 to create a new item, otherwise modify existing function registerItem(uint _type, uint _id, bytes32 _ipfs, bytes32 _name, bytes32 _meta) onlyRegistered { // XXX _type sanity check? var item = items[_type][_id]; if (_id != 0) require(item.owner == msg.sender); else { // XXX: what about overflow here? var newId = ++counts[_type]; item = items[_type][newId]; item.id = newId; item.itemType = ItemType(_type); item.owner = msg.sender; accounts[msg.sender].items[_type].push(item.id); } item.name = _name; item.meta = _meta; item.ipfs = _ipfs; if (_id == 0) LogItemRegistered( item.owner, uint(item.itemType), item.id, item.ipfs, item.name, item.meta ); else LogItemModified( item.owner, uint(item.itemType), item.id, item.ipfs, item.name, item.meta ); } // NOTE // There's no real point of un-registering items // Campaigns need to be kept anyway, as well as ad units // END NOTE // // Constant functions // function isRegistered(address who) public constant returns (bool) { var acc = accounts[who]; return acc.addr != 0; } // Functions exposed for web3 interface // NOTE: this is sticking to the policy of keeping static-sized values at the left side of tuples function getAccount(address _acc) constant public returns (address, bytes32, bytes32, bytes32) { var acc = accounts[_acc]; require(acc.addr != 0); return (acc.wallet, acc.ipfs, acc.name, acc.meta); } function getAccountItems(address _acc, uint _type) constant public returns (uint[]) { var acc = accounts[_acc]; require(acc.addr != 0); return acc.items[_type]; } function getItem(uint _type, uint _id) constant public returns (address, bytes32, bytes32, bytes32) { var item = items[_type][_id]; require(item.id != 0); return (item.owner, item.ipfs, item.name, item.meta); } function hasItem(uint _type, uint _id) constant public returns (bool) { var item = items[_type][_id]; return item.id != 0; } // Events event LogAccountRegistered(address addr, address wallet, bytes32 ipfs, bytes32 accountName, bytes32 meta, bytes32 signature); event LogAccountModified(address addr, address wallet, bytes32 ipfs, bytes32 accountName, bytes32 meta, bytes32 signature); event LogItemRegistered(address owner, uint itemType, uint id, bytes32 ipfs, bytes32 itemName, bytes32 meta); event LogItemModified(address owner, uint itemType, uint id, bytes32 ipfs, bytes32 itemName, bytes32 meta); } contract ADXExchange is Ownable, Drainable { string public name = "AdEx Exchange"; ERC20 public token; ADXRegistry public registry; uint public bidsCount; mapping (uint => Bid) bidsById; mapping (uint => uint[]) bidsByAdunit; // bids set out by ad unit mapping (uint => uint[]) bidsByAdslot; // accepted by publisher, by ad slot // TODO: some properties in the bid structure - achievedPoints/peers for example - are not used atm // CONSIDER: the bid having a adunitType so that this can be filtered out // WHY IT'S NOT IMPORTANT: you can get bids by ad units / ad slots, which is filter enough already considering we know their types // CONSIDER: locking ad units / ad slots or certain properties from them so that bids cannot be ruined by editing them // WHY IT'S NOT IMPORTANT: from a game theoretical point of view there's no incentive to do that // corresponds to enum types in ADXRegistry uint constant ADUNIT = 0; uint constant ADSLOT = 1; enum BidState { Open, Accepted, // in progress // the following states MUST unlock the ADX amount (return to advertiser) // fail states Canceled, Expired, // success states Completed, Claimed } struct Bid { uint id; BidState state; // ADX reward amount uint amount; // Links on advertiser side address advertiser; address advertiserWallet; uint adUnit; bytes32 adUnitIpfs; bytes32 advertiserPeer; // Links on publisher side address publisher; address publisherWallet; uint adSlot; bytes32 adSlotIpfs; bytes32 publisherPeer; uint acceptedTime; // when was it accepted by a publisher // Requirements //RequirementType type; uint requiredPoints; // how many impressions/clicks/conversions have to be done uint requiredExecTime; // essentially a timeout // Results bool confirmedByPublisher; bool confirmedByAdvertiser; // IPFS links to result reports bytes32 publisherReportIpfs; bytes32 advertiserReportIpfs; } // // MODIFIERS // modifier onlyRegisteredAcc() { require(registry.isRegistered(msg.sender)); _; } modifier onlyBidOwner(uint _bidId) { require(msg.sender == bidsById[_bidId].advertiser); _; } modifier onlyBidAceptee(uint _bidId) { require(msg.sender == bidsById[_bidId].publisher); _; } modifier onlyBidState(uint _bidId, BidState _state) { require(bidsById[_bidId].id != 0); require(bidsById[_bidId].state == _state); _; } modifier onlyExistingBid(uint _bidId) { require(bidsById[_bidId].id != 0); _; } // Functions function ADXExchange(address _token, address _registry) { token = ERC20(_token); registry = ADXRegistry(_registry); } // // Bid actions // // the bid is placed by the advertiser function placeBid(uint _adunitId, uint _target, uint _rewardAmount, uint _timeout, bytes32 _peer) onlyRegisteredAcc { bytes32 adIpfs; address advertiser; address advertiserWallet; // NOTE: those will throw if the ad or respectively the account do not exist (advertiser,adIpfs,,) = registry.getItem(ADUNIT, _adunitId); (advertiserWallet,,,) = registry.getAccount(advertiser); // XXX: maybe it could be a feature to allow advertisers bidding on other advertisers' ad units, but it will complicate things... require(advertiser == msg.sender); Bid memory bid; bid.id = ++bidsCount; // start from 1, so that 0 is not a valid ID bid.state = BidState.Open; // XXX redundant, but done for code clarity bid.amount = _rewardAmount; bid.advertiser = advertiser; bid.advertiserWallet = advertiserWallet; bid.adUnit = _adunitId; bid.adUnitIpfs = adIpfs; bid.requiredPoints = _target; bid.requiredExecTime = _timeout; bid.advertiserPeer = _peer; bidsById[bid.id] = bid; bidsByAdunit[_adunitId].push(bid.id); require(token.transferFrom(advertiserWallet, address(this), _rewardAmount)); LogBidOpened(bid.id, advertiser, _adunitId, adIpfs, _target, _rewardAmount, _timeout, _peer); } // the bid is canceled by the advertiser function cancelBid(uint _bidId) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidOwner(_bidId) onlyBidState(_bidId, BidState.Open) { Bid storage bid = bidsById[_bidId]; bid.state = BidState.Canceled; require(token.transfer(bid.advertiserWallet, bid.amount)); LogBidCanceled(bid.id); } // a bid is accepted by a publisher for a given ad slot function acceptBid(uint _bidId, uint _slotId, bytes32 _peer) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidState(_bidId, BidState.Open) { address publisher; address publisherWallet; bytes32 adSlotIpfs; // NOTE: those will throw if the ad slot or respectively the account do not exist (publisher,adSlotIpfs,,) = registry.getItem(ADSLOT, _slotId); (publisherWallet,,,) = registry.getAccount(publisher); require(publisher == msg.sender); Bid storage bid = bidsById[_bidId]; // should not happen when bid.state is BidState.Open, but just in case require(bid.publisher == 0); bid.state = BidState.Accepted; bid.publisher = publisher; bid.publisherWallet = publisherWallet; bid.adSlot = _slotId; bid.adSlotIpfs = adSlotIpfs; bid.publisherPeer = _peer; bid.acceptedTime = now; bidsByAdslot[_slotId].push(_bidId); LogBidAccepted(bid.id, publisher, _slotId, adSlotIpfs, bid.acceptedTime, bid.publisherPeer); } // the bid is given up by the publisher, therefore canceling it and returning the funds to the advertiser // same logic as cancelBid(), but different permissions function giveupBid(uint _bidId) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidAceptee(_bidId) onlyBidState(_bidId, BidState.Accepted) { var bid = bidsById[_bidId]; bid.state = BidState.Canceled; require(token.transfer(bid.advertiserWallet, bid.amount)); LogBidCanceled(bid.id); } // both publisher and advertiser have to call this for a bid to be considered verified function verifyBid(uint _bidId, bytes32 _report) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidState(_bidId, BidState.Accepted) { Bid storage bid = bidsById[_bidId]; require(bid.publisher == msg.sender || bid.advertiser == msg.sender); if (bid.publisher == msg.sender) { bid.confirmedByPublisher = true; bid.publisherReportIpfs = _report; } if (bid.advertiser == msg.sender) { bid.confirmedByAdvertiser = true; bid.advertiserReportIpfs = _report; } if (bid.confirmedByAdvertiser && bid.confirmedByPublisher) { bid.state = BidState.Completed; LogBidCompleted(bid.id, bid.advertiserReportIpfs, bid.publisherReportIpfs); } } // now, claim the reward; callable by the publisher; // claimBidReward is a separate function so as to define clearly who pays the gas for transfering the reward function claimBidReward(uint _bidId) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidAceptee(_bidId) onlyBidState(_bidId, BidState.Completed) { Bid storage bid = bidsById[_bidId]; bid.state = BidState.Claimed; require(token.transfer(bid.publisherWallet, bid.amount)); LogBidRewardClaimed(bid.id, bid.publisherWallet, bid.amount); } // This can be done if a bid is accepted, but expired // This is essentially the protection from never settling on verification, or from publisher not executing the bid within a reasonable time function refundBid(uint _bidId) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidOwner(_bidId) onlyBidState(_bidId, BidState.Accepted) { Bid storage bid = bidsById[_bidId]; require(bid.requiredExecTime > 0); // you can't refund if you haven't set a timeout require(SafeMath.add(bid.acceptedTime, bid.requiredExecTime) < now); bid.state = BidState.Expired; require(token.transfer(bid.advertiserWallet, bid.amount)); LogBidExpired(bid.id); } // // Public constant functions // function getBidsFromArr(uint[] arr, uint _state) internal returns (uint[] _all) { BidState state = BidState(_state); // separate array is needed because of solidity stupidity (pun intended ))) ) uint[] memory all = new uint[](arr.length); uint count = 0; uint i; for (i = 0; i < arr.length; i++) { var id = arr[i]; var bid = bidsById[id]; if (bid.state == state) { all[count] = id; count += 1; } } _all = new uint[](count); for (i = 0; i < count; i++) _all[i] = all[i]; } function getAllBidsByAdunit(uint _adunitId) constant external returns (uint[]) { return bidsByAdunit[_adunitId]; } function getBidsByAdunit(uint _adunitId, uint _state) constant external returns (uint[]) { return getBidsFromArr(bidsByAdunit[_adunitId], _state); } function getAllBidsByAdslot(uint _adslotId) constant external returns (uint[]) { return bidsByAdslot[_adslotId]; } function getBidsByAdslot(uint _adslotId, uint _state) constant external returns (uint[]) { return getBidsFromArr(bidsByAdslot[_adslotId], _state); } function getBid(uint _bidId) onlyExistingBid(_bidId) constant external returns ( uint, uint, uint, uint, uint, // advertiser (ad unit, ipfs, peer) uint, bytes32, bytes32, // publisher (ad slot, ipfs, peer) uint, bytes32, bytes32 ) { var bid = bidsById[_bidId]; return ( uint(bid.state), bid.requiredPoints, bid.requiredExecTime, bid.amount, bid.acceptedTime, bid.adUnit, bid.adUnitIpfs, bid.advertiserPeer, bid.adSlot, bid.adSlotIpfs, bid.publisherPeer ); } function getBidReports(uint _bidId) onlyExistingBid(_bidId) constant external returns ( bytes32, // advertiser report bytes32 // publisher report ) { var bid = bidsById[_bidId]; return (bid.advertiserReportIpfs, bid.publisherReportIpfs); } // // Events // event LogBidOpened(uint bidId, address advertiser, uint adunitId, bytes32 adunitIpfs, uint target, uint rewardAmount, uint timeout, bytes32 advertiserPeer); event LogBidAccepted(uint bidId, address publisher, uint adslotId, bytes32 adslotIpfs, uint acceptedTime, bytes32 publisherPeer); event LogBidCanceled(uint bidId); event LogBidExpired(uint bidId); event LogBidCompleted(uint bidId, bytes32 advReport, bytes32 pubReport); event LogBidRewardClaimed(uint _bidId, address _wallet, uint _amount); }
This can be done if a bid is accepted, but expired This is essentially the protection from never settling on verification, or from publisher not executing the bid within a reasonable time
function refundBid(uint _bidId) onlyRegisteredAcc onlyExistingBid(_bidId) onlyBidOwner(_bidId) onlyBidState(_bidId, BidState.Accepted) { Bid storage bid = bidsById[_bidId]; require(SafeMath.add(bid.acceptedTime, bid.requiredExecTime) < now); bid.state = BidState.Expired; require(token.transfer(bid.advertiserWallet, bid.amount)); LogBidExpired(bid.id); }
6,398,717
[ 1, 2503, 848, 506, 2731, 309, 279, 9949, 353, 8494, 16, 1496, 7708, 1220, 353, 18518, 11220, 326, 17862, 628, 5903, 26319, 2456, 603, 11805, 16, 578, 628, 12855, 486, 11274, 326, 9949, 3470, 279, 23589, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 16255, 17763, 12, 11890, 389, 19773, 548, 13, 203, 202, 202, 3700, 10868, 8973, 203, 202, 202, 3700, 9895, 17763, 24899, 19773, 548, 13, 203, 202, 202, 3700, 17763, 5541, 24899, 19773, 548, 13, 203, 202, 202, 3700, 17763, 1119, 24899, 19773, 548, 16, 605, 350, 1119, 18, 18047, 13, 203, 202, 95, 203, 202, 202, 17763, 2502, 9949, 273, 30534, 5132, 63, 67, 19773, 548, 15533, 203, 202, 202, 6528, 12, 9890, 10477, 18, 1289, 12, 19773, 18, 23847, 950, 16, 9949, 18, 4718, 1905, 950, 13, 411, 2037, 1769, 203, 203, 202, 202, 19773, 18, 2019, 273, 605, 350, 1119, 18, 10556, 31, 203, 202, 202, 6528, 12, 2316, 18, 13866, 12, 19773, 18, 361, 1097, 15914, 16936, 16, 9949, 18, 8949, 10019, 203, 203, 202, 202, 1343, 17763, 10556, 12, 19773, 18, 350, 1769, 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 ]
./partial_match/1/0x0241855466D655e9EA5D195f55f1e11ED047AB0F/sources/DT.sol
消毁币 检查当前帐号余额是否足够 检查_value是否有效 从sender账户中中减去一定数量的token 更新发行币的总量 消币成功后触发Burn事件,并返回true
function burn(uint256 _value) public returns (bool success) { assert(balanceOf[msg.sender] >= _value); assert(_value > 0); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); totalSupply = SafeMath.safeSub(totalSupply,_value); emit Burn(msg.sender, _value); return true; }
3,918,949
[ 1, 167, 119, 235, 167, 112, 228, 166, 121, 228, 225, 167, 101, 227, 167, 258, 103, 166, 126, 246, 166, 236, 240, 166, 121, 243, 166, 242, 120, 165, 126, 252, 170, 100, 256, 167, 251, 112, 166, 243, 104, 169, 119, 116, 166, 102, 258, 225, 167, 101, 227, 167, 258, 103, 67, 1132, 167, 251, 112, 166, 243, 104, 167, 255, 236, 167, 248, 235, 225, 165, 124, 241, 15330, 169, 117, 104, 167, 235, 120, 165, 121, 260, 165, 121, 260, 166, 234, 242, 166, 241, 124, 165, 121, 227, 166, 111, 253, 167, 248, 113, 170, 234, 242, 168, 253, 231, 2316, 225, 167, 254, 117, 167, 249, 113, 166, 242, 244, 169, 99, 239, 166, 121, 228, 168, 253, 231, 167, 227, 124, 170, 234, 242, 225, 167, 119, 235, 166, 121, 228, 167, 235, 243, 166, 237, 258, 166, 243, 241, 169, 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, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1815, 12, 12296, 951, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 203, 3639, 1815, 24899, 1132, 405, 374, 1769, 203, 3639, 11013, 951, 63, 3576, 18, 15330, 65, 273, 14060, 10477, 18, 4626, 1676, 12, 12296, 951, 63, 3576, 18, 15330, 6487, 389, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 14060, 10477, 18, 4626, 1676, 12, 4963, 3088, 1283, 16, 67, 1132, 1769, 203, 3639, 3626, 605, 321, 12, 3576, 18, 15330, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 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 ]
./full_match/80001/0x7717aB77bf46033626CCF17366015A867f6FC9b2/sources/project:/contracts/superfluid/SuperfluidPool.sol
TODO transferability of admin should be allowed nft transferable? customizable metadata for the NFT can be considered solhint-disable-next-line no-empty-blocks What happens to the Admin NFT?
function transferAdmin(address admin_) external { }
5,577,494
[ 1, 6241, 7412, 2967, 434, 3981, 1410, 506, 2935, 290, 1222, 7412, 429, 35, 1679, 6934, 1982, 364, 326, 423, 4464, 848, 506, 7399, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 5531, 17, 7996, 18734, 10555, 358, 326, 7807, 423, 4464, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 4446, 12, 2867, 3981, 67, 13, 3903, 288, 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 ]
./full_match/80001/0xF7D2ABDc8e53800C6DDFaaDe63E45d5a100fF6DA/sources/project_/contracts/Platform/XG_Game_ERC721A.sol
@notice Opensea contract-level metadata @dev Return contract URI for Opensea @return contractURI (string memory) Returns contract URI
function contractURI() public view returns (string memory) { return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, "games/", gameId.toString())) : ""; }
848,665
[ 1, 3678, 307, 69, 6835, 17, 2815, 1982, 225, 2000, 6835, 3699, 364, 3502, 307, 69, 327, 6835, 3098, 261, 1080, 3778, 13, 2860, 6835, 3699, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6835, 3098, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 1731, 12, 1969, 3098, 2934, 2469, 405, 374, 203, 7734, 692, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 3098, 16, 315, 75, 753, 19, 3113, 7920, 548, 18, 10492, 1435, 3719, 203, 7734, 294, 1408, 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 ]
pragma solidity >=0.5.0; // import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address public contractOwner; bool private operational = true; mapping(address => bool) private authorizedCallers; // AIRLINES mapping(address => Airline) public airlines; uint256 public numAirlines = 0; address[] public airlineAddresses; uint256 airlineId = 1; mapping(address => bool) private authorizedAirlines; uint256 public numAuthorizedAirlines = 0; address[] public authorizedAirlinesArray; mapping(address => mapping(address => bool)) public airlineVotes; // registered airline to unregistered airline to yes or not vote struct Airline { address airlineAddress; uint256 id; string name; bool isRegistered; uint256 insuranceMoney; uint256 votes; bool exists; } // FLIGHTS mapping(string => Flight) public flights; uint256 public numFlights = 0; string[] public flightNameArray; struct Flight { string airline; string flight; uint256 departureTime; uint256 price; uint8 statusCode; bool isRegistered; bool exists; } // PASSENGERS mapping(address => Passenger) public passengers; address[] public passengerAddresses; uint256 public numPassengers = 0; mapping(address => mapping(string => uint256)) public passengerFlightInsurance; // passenger address => flightId to insurance purchased mapping(address => string[]) public passengerFlightsPurchased; mapping(address => uint256) public numFlightsPurchased; struct Passenger { address passengerAddress; uint256 credit; bool exists; } // CONSTANTS uint256 public constant INSURANCE_PRICE_LIMIT = 1 ether; uint256 public constant MIN_ANTE = 10 ether; uint8 private constant MULTIPARTY_MIN_AIRLINES = 4; // FLIGHT STATUS CODES uint8 private constant STATUS_CODE_UNKNOWN = 0; uint8 private constant STATUS_CODE_ON_TIME = 10; uint8 private constant STATUS_CODE_LATE_AIRLINE = 20; uint8 private constant STATUS_CODE_LATE_WEATHER = 30; uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40; uint8 private constant STATUS_CODE_LATE_OTHER = 50; /********************************************************************************************/ /* GETTERS AND SETTERS */ /********************************************************************************************/ /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event AirlineRegistered( address airlineAddress, uint256 id, string name, bool isRegistered ); event AirlineAuthorized(address airlineAddress, string name); event AirlineInRegistrationQueue(address airline, string name); event AirlineVote(address voter, address votee); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor() public { contractOwner = msg.sender; string memory name = "first"; airlines[contractOwner] = Airline({ airlineAddress: contractOwner, id: airlineId++, name: name, isRegistered: true, insuranceMoney: 0, votes: 0, exists: true }); emit AirlineRegistered( contractOwner, airlines[contractOwner].id, name, true ); numAirlines = 1; airlineAddresses.push(contractOwner); // authorizeAirline(contractOwner); // cannot call because this has a modifier that requires the caller to be an authorized airline already authorizedAirlines[contractOwner] = true; authorizedAirlinesArray.push(contractOwner); numAuthorizedAirlines = 1; emit AirlineAuthorized(contractOwner, "first"); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // ADMIN modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier isAuthorizedCaller() { require( authorizedCallers[msg.sender] == true, "Address is not authorized to make calls on data contract" ); _; } // AIRLINE // Requires the airline to be registered and have an insurance fund of at least 10 ETH modifier requireAuthorizedAirline(address airlineAddress) { require( authorizedAirlines[airlineAddress] == true, "Caller is not an authorized airline." ); _; } modifier requireVoterHasntVotedForAirline( address votingAirlineAddress, address airlineAddress ) { require( airlineVotes[votingAirlineAddress][airlineAddress] == false, "The msg.sender has already voted to authorize the airline." ); _; } modifier requirePayment() { require(msg.value > 0, "This function requires an ether payment."); _; } modifier requirePassengerExists(address passenger) { require( passengers[passenger].exists == true, "The passenger does not exist." ); _; } modifier requireAirlineExists(address airlineAddress) { require( airlines[airlineAddress].exists == true, "The airline does not exist." ); _; } modifier requireAirlineDoesNotExist(address airlineAddress) { require( airlines[airlineAddress].exists == false, "The airline does not exist." ); _; } modifier requireAirlineIsNotRegistered(address airlineAddress) { require( airlines[airlineAddress].isRegistered == false, "The airline is already registered." ); _; } modifier requireAirlineInsurance() { require( isAirlineInsured(msg.sender), "Airline has not put up the required insurance." ); _; } // FLIGHT modifier requireRegisteredFlight(string memory flight) { require(isFlightRegistered(flight), "Flight is not registered."); _; } modifier requireValidDepartureTime(uint256 departureTime) { require(departureTime > now, "Departure time cannot be in the past."); _; } modifier requireFlightIsNotAlreadyRegistered(string memory flightId) { require(!flights[flightId].exists, "Flight Id already registered."); _; } // PASSENGER modifier requireAvailableCredit(address passenger) { require( passengers[passenger].credit > 0, "The passenger does not have credit available" ); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ // ADMIN function isOperational() public view returns (bool) { return operational; } function setOperatingStatus(bool mode) external requireContractOwner { operational = mode; } function authorizeCaller(address addressToAuthorize) external requireContractOwner() { authorizedCallers[addressToAuthorize] = true; } // AIRLINE /** * @dev Gives an airline authority to register flights */ function authorizeAirline(address sender, address airlineAddress) internal requireIsOperational { authorizedAirlines[airlineAddress] = true; authorizedAirlinesArray.push(airlineAddress); numAuthorizedAirlines += 1; } /** * @dev Strips an airline of the authority to register flights */ function deauthorizeAirline(address sender, address airlineAddress) internal requireIsOperational { delete authorizedAirlines[airlineAddress]; for (uint256 i = 0; i < authorizedAirlinesArray.length; i++) { if (authorizedAirlinesArray[i] == airlineAddress) { delete authorizedAirlinesArray[i]; numAuthorizedAirlines--; } } } function getVotes(address airlineAddress) public requireIsOperational returns (uint256) { return airlines[airlineAddress].votes; } function doesAirlineExist(address airlineAddress) public requireIsOperational returns (bool) { if (airlines[airlineAddress].exists == true) return true; else return false; } function doesAirlineMeetAuthorizationRequirements(address airlineAddress) internal requireIsOperational returns (bool) { if ( isAirlineRegistered(airlineAddress) && isAirlineInsured(airlineAddress) ) return true; else return false; } function doesSenderMeetAuthorizationRequirements() internal requireIsOperational returns (bool) { if (isAirlineRegistered(msg.sender) && isAirlineInsured(msg.sender)) return true; else return false; } function isAirlineRegistered(address airlineAddress) public requireIsOperational returns (bool) { return airlines[airlineAddress].isRegistered; } function isAirlineInsured(address airlineAddress) public requireIsOperational returns (bool) { return airlines[airlineAddress].insuranceMoney > 10; // 1000000000000000000 18 0s } function doesAirlineHaveEnoughVotes(address airlineAddress) internal requireIsOperational returns (bool) { if (!isVotingRequiredForRegistration()) return true; else { uint256 voteThreshold = uint256(MULTIPARTY_MIN_AIRLINES).div(2); return airlines[airlineAddress].votes > voteThreshold; } } function isVotingRequiredForRegistration() internal requireIsOperational returns (bool) { return numAirlines >= MULTIPARTY_MIN_AIRLINES; } // FLIGHT function isFlightRegistered(string memory flight) public requireIsOperational returns (bool) { return flights[flight].isRegistered; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /********************************************************************************************/ // AIRLINE FUNCTIONS /********************************************************************************************/ /** * @dev Add an airline to the registration queue */ function registerAirline( address sender, address airlineAddress, string calldata name ) external requireIsOperational requireAirlineDoesNotExist(airlineAddress) requireAuthorizedAirline(sender) returns (bool success, bool isRegistered) { bool isRegistered = doesAirlineHaveEnoughVotes(airlineAddress) ? true : false; airlines[airlineAddress] = Airline({ airlineAddress: airlineAddress, id: airlineId++, name: name, isRegistered: isRegistered, insuranceMoney: 0, votes: 0, exists: true }); emit AirlineRegistered( airlineAddress, airlines[airlineAddress].id, name, isRegistered ); numAirlines++; airlineAddresses.push(airlineAddress); return (true, isRegistered); } function vote(address votingAirlineAddress, address airlineAddress) public requireIsOperational requireAirlineExists(airlineAddress) requireAirlineIsNotRegistered(airlineAddress) requireVoterHasntVotedForAirline(votingAirlineAddress, airlineAddress) requireAuthorizedAirline(votingAirlineAddress) returns (uint256) { airlines[airlineAddress].votes = airlines[airlineAddress].votes.add(1); airlineVotes[votingAirlineAddress][airlineAddress] = true; emit AirlineVote(votingAirlineAddress, airlineAddress); if (doesAirlineHaveEnoughVotes(airlineAddress)) { airlines[airlineAddress].isRegistered = true; emit AirlineRegistered( airlineAddress, airlines[airlineAddress].id, airlines[airlineAddress].name, true ); } if (doesAirlineMeetAuthorizationRequirements(airlineAddress)) { authorizeAirline(votingAirlineAddress, airlineAddress); emit AirlineAuthorized( airlineAddress, airlines[airlineAddress].name ); } return airlines[airlineAddress].votes; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining */ function fund(address airlineAddress) public payable requireIsOperational requireAirlineExists(airlineAddress) requirePayment { uint256 currentInsuranceMoney = airlines[airlineAddress].insuranceMoney; airlines[airlineAddress].insuranceMoney = currentInsuranceMoney.add( msg.value ); if (doesAirlineMeetAuthorizationRequirements(airlineAddress)) { authorizeAirline(airlineAddress, airlineAddress); emit AirlineAuthorized( airlineAddress, airlines[airlineAddress].name ); } } /********************************************************************************************/ // FLIGHT FUNCTIONS /********************************************************************************************/ /** * @dev Register a future flight for insuring. */ function registerFlight( address sender, string calldata airline, string calldata flight, uint256 departureTime, uint256 price ) external requireIsOperational requireAuthorizedAirline(sender) requireValidDepartureTime(departureTime) requireFlightIsNotAlreadyRegistered(flight) { // bytes32 key = getFlight(msg.sender, flight, timestamp); // use key instead of Id // require(!flights[flight].exists, "Flight already registered."); // TODO: Validate that the sender is registering a flight for itself because it shouldnt // be registering a flight for another airline that is not authorized and insured // require(sender != airlines[airlineAddress], 'Registering a flight for another airline is prohibited'); flights[flight] = Flight({ airline: airline, flight: flight, departureTime: departureTime, price: price, statusCode: STATUS_CODE_ON_TIME, isRegistered: true, exists: true }); flightNameArray.push(flight); numFlights++; } // function getFlightKey // ( // address airline, // string flight, // uint256 timestamp // ) // pure // internal // returns(bytes32) // { // return keccak256(abi.encodePacked(airline, flight, timestamp)); // } /********************************************************************************************/ // PASSSENGER FUNCTIONS /********************************************************************************************/ /** * @dev Buy insurance for a flight * */ function buyFlightInsurance( string calldata flightId, address payable passengerAddress ) external payable requireIsOperational // returns (uint256, address, uint256) { uint256 insurancePurchased = msg.value; uint256 refund = 0; if (msg.value > INSURANCE_PRICE_LIMIT) { insurancePurchased = INSURANCE_PRICE_LIMIT; refund = msg.value.sub(INSURANCE_PRICE_LIMIT); passengerAddress.transfer(refund); } if (!passengers[passengerAddress].exists) { passengers[passengerAddress] = Passenger({ passengerAddress: passengerAddress, credit: 0, exists: true }); passengerAddresses.push(passengerAddress); numPassengers++; } passengerFlightsPurchased[passengerAddress].push(flightId); // record flightId of purchased flight numFlightsPurchased[passengerAddress]++; passengerFlightInsurance[passengerAddress][flightId] = insurancePurchased; // record flight insurance purchased } /** * @dev Credits payouts to insurees */ function creditPassengers(string memory flightId) internal requireIsOperational { for (uint256 i = 0; i < passengerAddresses.length; i++) { address passengerAddress = passengerAddresses[i]; uint256 flightInsurancePurchased = passengerFlightInsurance[passengerAddress][flightId]; if (flightInsurancePurchased > 0) { uint256 currentCredit = passengers[passengerAddress].credit; passengerFlightInsurance[passengerAddress][flightId] = 0; passengers[passengerAddress].credit = currentCredit.add( flightInsurancePurchased.mul(3).div(2) ); } } // TODO: Check if any airlines have lost their authorized status because they had to payout from their insurance money and they have less than they are suppose to } /** * @dev Transfers eligible payout funds to insuree * */ function withdraw(address payable passenger) external requireIsOperational requirePassengerExists(passenger) requireAvailableCredit(passenger) { uint256 credit = passengers[passenger].credit; uint256 currentBalance = address(this).balance; require( currentBalance >= credit, "The contract does not have enough ether to pay the passenger." ); passengers[passenger].credit = 0; passenger.transfer(credit); } /********************************************************************************************/ // ORACLE FUNCTIONS /********************************************************************************************/ function processFlightStatus( string calldata flightId, uint256 departureTime, uint8 statusCode ) external requireIsOperational requireRegisteredFlight(flightId) { // flights[flightId].departureTime = departureTime; flights[flightId].statusCode = statusCode; if (statusCode == STATUS_CODE_LATE_AIRLINE) creditPassengers(flightId); } // function updateFlightDepartureTime // ( // string flight // uint256 departureTime // ) // { // flights[flight].departureTime = departureTime; // } // function updateFlightStatus // ( // string flight // uint8 status // ) // { // flights[flight].status = status; // } /** * @dev Fallback function for funding smart contract. * */ function() external payable { // fund(); } }
record flight insurance purchased
passengerFlightInsurance[passengerAddress][flightId] = insurancePurchased;
15,868,527
[ 1, 3366, 25187, 2763, 295, 1359, 5405, 343, 8905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1342, 14348, 24243, 5048, 295, 1359, 63, 5466, 14348, 1887, 6362, 19131, 548, 65, 273, 2763, 295, 1359, 10262, 343, 8905, 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 ]
// SPDX-License-Identifier: MIT pragma solidity =0.7.6; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol"; import {IWPowerPerp} from "../interfaces/IWPowerPerp.sol"; /** * @notice ERC20 Token representing wrapped long power perpetual position * @dev value of power perpetual is expected to go down over time through the impact of funding */ contract WPowerPerp is ERC20, Initializable, IWPowerPerp { address public controller; /** * @notice long power perpetual constructor * @param _name token name for ERC20 * @param _symbol token symbol for ERC20 */ constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {} modifier onlyController() { require(msg.sender == controller, "Not controller"); _; } /** * @notice init wPowerPerp contract * @param _controller controller address */ function init(address _controller) external initializer { require(_controller != address(0), "Invalid controller address"); controller = _controller; } /** * @notice mint wPowerPerp * @param _account account to mint to * @param _amount amount to mint */ function mint(address _account, uint256 _amount) external override onlyController { _mint(_account, _amount); } /** * @notice burn wPowerPerp * @param _account account to burn from * @param _amount amount to burn */ function burn(address _account, uint256 _amount) external override onlyController { _burn(_account, _amount); } }
* @notice init wPowerPerp contract @param _controller controller address/
function init(address _controller) external initializer { require(_controller != address(0), "Invalid controller address"); controller = _controller; }
12,896,372
[ 1, 2738, 341, 13788, 2173, 84, 6835, 225, 389, 5723, 2596, 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 ]
[ 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, 1208, 12, 2867, 389, 5723, 13, 3903, 12562, 288, 203, 3639, 2583, 24899, 5723, 480, 1758, 12, 20, 3631, 315, 1941, 2596, 1758, 8863, 203, 3639, 2596, 273, 389, 5723, 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 ]
pragma solidity >=0.4.23; /// @title Math operations with safety checks /// @author Melonport AG <[email protected]> /// @notice From https://github.com/status-im/status-network-token/blob/master/contracts/safeMath.sol 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) { uint 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; } } /// @title ERC20 Token Interface /// @author Melonport AG <[email protected]> /// @notice See https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // EVENTS event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // CONSTANT METHODS function totalSupply() constant returns (uint256 totalSupply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} // NON-CONSTANT METHODS function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} } /// @title ERC20 Token /// @author Melonport AG <[email protected]> /// @notice Original taken from https://github.com/ethereum/EIPs/issues/20 /// @notice Checked against integer overflow contract ERC20 is ERC20Interface { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { throw; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { throw; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { // See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263555598 if (_value > 0) { require(allowed[msg.sender][_spender] == 0); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract CouncilVesting { using safeMath for uint; // FIELDS // Constructor fields ERC20 public MELON_CONTRACT; // MLN as ERC20 contract address public owner; // deployer; can interrupt vesting // Methods fields bool public interrupted; // whether vesting is still possible bool public isVestingStarted; // whether vesting period has begun uint public totalVestingAmount; // quantity of vested Melon in total uint public vestingStartTime; // timestamp when vesting is set uint public vestingPeriod; // total vesting period in seconds address public beneficiary; // address of the beneficiary uint public withdrawn; // quantity of Melon withdrawn so far // MODIFIERS modifier not_interrupted() { require( !interrupted, "The contract has been interrupted" ); _; } modifier only_owner() { require( msg.sender == owner, "Only owner can do this" ); _; } modifier only_beneficiary() { require( msg.sender == beneficiary, "Only beneficiary can do this" ); _; } modifier vesting_not_started() { require( !isVestingStarted, "Vesting cannot be started" ); _; } modifier vesting_started() { require( isVestingStarted, "Vesting must be started" ); _; } /// @notice Calculates the quantity of Melon asset that's currently withdrawable /// @return withdrawable Quantity of withdrawable Melon asset function calculateWithdrawable() public view returns (uint withdrawable) { uint timePassed = block.timestamp.sub(vestingStartTime); if (timePassed < vestingPeriod) { uint vested = totalVestingAmount.mul(timePassed).div(vestingPeriod); withdrawable = vested.sub(withdrawn); } else { withdrawable = totalVestingAmount.sub(withdrawn); } } // NON-CONSTANT METHODS /// @param ofMelonAsset Address of Melon asset constructor(address ofMelonAsset, address ofOwner) { MELON_CONTRACT = ERC20(ofMelonAsset); owner = ofOwner; } /// @param ofBeneficiary Address of beneficiary /// @param ofMelonQuantity Address of MLN asset /// @param ofVestingPeriod Vesting period in seconds from vestingStartTime function setVesting( address ofBeneficiary, uint ofMelonQuantity, uint ofVestingPeriod ) external only_owner not_interrupted vesting_not_started { require(ofMelonQuantity > 0, "Must vest some MLN"); require( MELON_CONTRACT.transferFrom(msg.sender, this, ofMelonQuantity), "MLN deposit failed" ); isVestingStarted = true; vestingStartTime = block.timestamp; totalVestingAmount = ofMelonQuantity; vestingPeriod = ofVestingPeriod; beneficiary = ofBeneficiary; } /// @notice Withdraw function withdraw() external only_beneficiary vesting_started not_interrupted { uint withdrawable = calculateWithdrawable(); withdrawn = withdrawn.add(withdrawable); require( MELON_CONTRACT.transfer(beneficiary, withdrawable), "Transfer to beneficiary failed" ); } /// @notice Withdraw vested tokens to beneficiary /// @notice Send remainder back to owner /// @notice Prevent further vesting function forceWithdrawalAndInterrupt() external only_owner vesting_started not_interrupted { interrupted = true; uint remainingVested = calculateWithdrawable(); uint totalToBeVested = withdrawn.add(remainingVested); uint remainingUnvested = totalVestingAmount.sub(totalToBeVested); withdrawn = totalVestingAmount; require( MELON_CONTRACT.transfer(beneficiary, remainingVested), "Transfer to beneficiary failed" ); require( MELON_CONTRACT.transfer(owner, remainingUnvested), "Transfer to owner failed" ); } }
quantity of Melon withdrawn so far
uint public withdrawn;
12,769,783
[ 1, 16172, 434, 490, 292, 265, 598, 9446, 82, 1427, 10247, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 1071, 598, 9446, 82, 31, 1850, 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/5/0x5a08edfCC269505A42fd594F7a00288E4E40BF4b/sources/lib/ERC721B/contracts/extensions/ERC721BBaseTokenURI.sol
* @dev ERC721B token where token URIs are determined with a base URI/
abstract contract ERC721BBaseTokenURI is ERC721B, IERC721Metadata { using Strings for uint256; string private _baseTokenURI; function tokenURI(uint256 tokenId) public view virtual returns(string memory) { if(!_exists(tokenId)) revert NonExistentToken(); string memory baseURI = _baseTokenURI; return bytes(baseURI).length > 0 ? string( abi.encodePacked(baseURI, tokenId.toString(), ".json") ) : ""; } function baseTokenURI() public view returns (string memory) { return _baseTokenURI; } function _setBaseURI(string memory uri) internal virtual { _baseTokenURI = uri; } }
1,867,378
[ 1, 654, 39, 27, 5340, 38, 1147, 1625, 1147, 24565, 854, 11383, 598, 279, 1026, 3699, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 27, 5340, 38, 2171, 1345, 3098, 353, 4232, 39, 27, 5340, 38, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 533, 3238, 389, 1969, 1345, 3098, 31, 203, 203, 203, 225, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 1135, 12, 1080, 3778, 13, 288, 203, 565, 309, 12, 5, 67, 1808, 12, 2316, 548, 3719, 15226, 3858, 4786, 319, 1345, 5621, 203, 565, 533, 3778, 1026, 3098, 273, 389, 1969, 1345, 3098, 31, 203, 565, 327, 1731, 12, 1969, 3098, 2934, 2469, 405, 374, 692, 533, 12, 203, 1377, 24126, 18, 3015, 4420, 329, 12, 1969, 3098, 16, 1147, 548, 18, 10492, 9334, 3552, 1977, 7923, 203, 565, 262, 294, 1408, 31, 203, 225, 289, 203, 21281, 225, 445, 1026, 1345, 3098, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 565, 327, 389, 1969, 1345, 3098, 31, 203, 225, 289, 203, 203, 225, 445, 389, 542, 2171, 3098, 12, 1080, 3778, 2003, 13, 2713, 5024, 288, 203, 565, 389, 1969, 1345, 3098, 273, 2003, 31, 203, 225, 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 ]
./partial_match/1/0xC8B4a74F7685e901D3c57a5Ec37aF8Ad450d8784/sources/PROGENS.sol
* @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); _Allowances[sender] = _Allowances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _Allowances[recipient] = _Allowances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
4,078,473
[ 1, 19297, 2430, 1375, 8949, 68, 628, 1375, 15330, 68, 358, 1375, 20367, 8338, 1220, 353, 2713, 445, 353, 7680, 358, 288, 13866, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 5859, 1147, 1656, 281, 16, 9026, 310, 1791, 28757, 16, 5527, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 29076, 30, 300, 1375, 15330, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 15330, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 20367, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 389, 7009, 6872, 63, 15330, 65, 273, 389, 7009, 6872, 63, 15330, 8009, 1717, 12, 8949, 16, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 11013, 8863, 203, 3639, 389, 7009, 6872, 63, 20367, 65, 273, 389, 7009, 6872, 63, 20367, 8009, 1289, 12, 8949, 1769, 203, 3639, 3626, 12279, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-01-31 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.11; /// @title ClonesWithImmutableArgs /// @author wighawag, zefram.eth /// @notice Enables creating clone contracts with immutable args library ClonesWithImmutableArgs { error CreateFail(); /// @notice Creates a clone proxy of the implementation contract, with immutable args /// @dev data cannot exceed 65535 bytes, since 2 bytes are used to store the data length /// @param implementation The implementation contract to clone /// @param data Encoded immutable args /// @return instance The address of the created clone function clone(address implementation, bytes memory data) internal returns (address instance) { // unrealistic for memory ptr or data length to exceed 256 bits unchecked { uint256 extraLength = data.length + 2; // +2 bytes for telling how much data there is appended to the call uint256 creationSize = 0x43 + extraLength; uint256 runSize = creationSize - 11; uint256 dataPtr; uint256 ptr; // solhint-disable-next-line no-inline-assembly assembly { ptr := mload(0x40) // ------------------------------------------------------------------------------------------------------------- // CREATION (11 bytes) // ------------------------------------------------------------------------------------------------------------- // 3d | RETURNDATASIZE | 0 | – // 61 runtime | PUSH2 runtime (r) | r 0 | – mstore( ptr, 0x3d61000000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x02), shl(240, runSize)) // size of the contract running bytecode (16 bits) // creation size = 0b // 80 | DUP1 | r r 0 | – // 60 creation | PUSH1 creation (c) | c r r 0 | – // 3d | RETURNDATASIZE | 0 c r r 0 | – // 39 | CODECOPY | r 0 | [0-2d]: runtime code // 81 | DUP2 | 0 c 0 | [0-2d]: runtime code // f3 | RETURN | 0 | [0-2d]: runtime code mstore( add(ptr, 0x04), 0x80600b3d3981f300000000000000000000000000000000000000000000000000 ) // ------------------------------------------------------------------------------------------------------------- // RUNTIME // ------------------------------------------------------------------------------------------------------------- // 36 | CALLDATASIZE | cds | – // 3d | RETURNDATASIZE | 0 cds | – // 3d | RETURNDATASIZE | 0 0 cds | – // 37 | CALLDATACOPY | – | [0, cds] = calldata // 61 | PUSH2 extra | extra | [0, cds] = calldata mstore( add(ptr, 0x0b), 0x363d3d3761000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x10), shl(240, extraLength)) // 60 0x38 | PUSH1 0x38 | 0x38 extra | [0, cds] = calldata // 0x38 (56) is runtime size - data // 36 | CALLDATASIZE | cds 0x38 extra | [0, cds] = calldata // 39 | CODECOPY | _ | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 0 0 | [0, cds] = calldata // 36 | CALLDATASIZE | cds 0 0 0 | [0, cds] = calldata // 61 extra | PUSH2 extra | extra cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x12), 0x603836393d3d3d36610000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x1b), shl(240, extraLength)) // 01 | ADD | cds+extra 0 0 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | 0 cds 0 0 0 | [0, cds] = calldata // 73 addr | PUSH20 0x123… | addr 0 cds 0 0 0 | [0, cds] = calldata mstore( add(ptr, 0x1d), 0x013d730000000000000000000000000000000000000000000000000000000000 ) mstore(add(ptr, 0x20), shl(0x60, implementation)) // 5a | GAS | gas addr 0 cds 0 0 0 | [0, cds] = calldata // f4 | DELEGATECALL | success 0 | [0, cds] = calldata // 3d | RETURNDATASIZE | rds success 0 | [0, cds] = calldata // 82 | DUP3 | 0 rds success 0 | [0, cds] = calldata // 80 | DUP1 | 0 0 rds success 0 | [0, cds] = calldata // 3e | RETURNDATACOPY | success 0 | [0, rds] = return data (there might be some irrelevant leftovers in memory [rds, cds] when rds < cds) // 90 | SWAP1 | 0 success | [0, rds] = return data // 3d | RETURNDATASIZE | rds 0 success | [0, rds] = return data // 91 | SWAP2 | success 0 rds | [0, rds] = return data // 60 0x36 | PUSH1 0x36 | 0x36 sucess 0 rds | [0, rds] = return data // 57 | JUMPI | 0 rds | [0, rds] = return data // fd | REVERT | – | [0, rds] = return data // 5b | JUMPDEST | 0 rds | [0, rds] = return data // f3 | RETURN | – | [0, rds] = return data mstore( add(ptr, 0x34), 0x5af43d82803e903d91603657fd5bf30000000000000000000000000000000000 ) } // ------------------------------------------------------------------------------------------------------------- // APPENDED DATA (Accessible from extcodecopy) // (but also send as appended data to the delegatecall) // ------------------------------------------------------------------------------------------------------------- extraLength -= 2; uint256 counter = extraLength; uint256 copyPtr = ptr + 0x43; // solhint-disable-next-line no-inline-assembly assembly { dataPtr := add(data, 32) } for (; counter >= 32; counter -= 32) { // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, mload(dataPtr)) } copyPtr += 32; dataPtr += 32; } uint256 mask = ~(256**(32 - counter) - 1); // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, and(mload(dataPtr), mask)) } copyPtr += counter; // solhint-disable-next-line no-inline-assembly assembly { mstore(copyPtr, shl(240, extraLength)) } // solhint-disable-next-line no-inline-assembly assembly { instance := create(0, ptr, creationSize) } if (instance == address(0)) { revert CreateFail(); } } } } /// @title Clone /// @author zefram.eth /// @notice Provides helper functions for reading immutable args from calldata contract Clone { /// @notice Reads an immutable arg with type address /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgAddress(uint256 argOffset) internal pure returns (address arg) { uint256 offset = _getImmutableArgsOffset(); assembly { arg := shr(0x60, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint256 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := calldataload(add(offset, argOffset)) } } /// @notice Reads an immutable arg with type uint64 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xc0, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint8 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xf8, calldataload(add(offset, argOffset))) } } /// @return offset The offset of the packed immutable args in calldata function _getImmutableArgsOffset() internal pure returns (uint256 offset) { // solhint-disable-next-line no-inline-assembly assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20Clone is Clone { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ function name() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0))); } function symbol() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0x20))); } function decimals() external pure returns (uint8) { return _getArgUint8(0x40); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// INTERNAL LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } } /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector. mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); unchecked { if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } } /// @title VestedERC20 /// @author zefram.eth /// @notice An ERC20 wrapper token that linearly vests an underlying token to /// its holders contract VestedERC20 is ERC20Clone { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using SafeTransferLib for ERC20; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_Wrap_VestOver(); error Error_Wrap_AmountTooLarge(); /// ----------------------------------------------------------------------- /// Storage variables /// ----------------------------------------------------------------------- /// @notice The amount of underlying tokens claimed by a token holder mapping(address => uint256) public claimedUnderlyingAmount; /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The token that is vested /// @return _underlying The address of the underlying token function underlying() public pure returns (address _underlying) { return _getArgAddress(0x41); } /// @notice The Unix timestamp (in seconds) of the start of the vest /// @return _startTimestamp The vest start timestamp function startTimestamp() public pure returns (uint64 _startTimestamp) { return _getArgUint64(0x55); } /// @notice The Unix timestamp (in seconds) of the end of the vest /// @return _endTimestamp The vest end timestamp function endTimestamp() public pure returns (uint64 _endTimestamp) { return _getArgUint64(0x5d); } /// ----------------------------------------------------------------------- /// User actions /// ----------------------------------------------------------------------- /// @notice Mints wrapped tokens using underlying tokens. Can only be called before the vest is over. /// @param underlyingAmount The amount of underlying tokens to wrap /// @param recipient The address that will receive the minted wrapped tokens /// @return wrappedTokenAmount The amount of wrapped tokens minted function wrap(uint256 underlyingAmount, address recipient) external returns (uint256 wrappedTokenAmount) { /// ------------------------------------------------------------------- /// Validation /// ------------------------------------------------------------------- uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp >= _endTimestamp) { revert Error_Wrap_VestOver(); } if ( underlyingAmount >= type(uint256).max / (_endTimestamp - _startTimestamp) ) { revert Error_Wrap_AmountTooLarge(); } /// ------------------------------------------------------------------- /// State updates /// ------------------------------------------------------------------- if (block.timestamp >= _startTimestamp) { // vest already started // wrappedTokenAmount * (endTimestamp() - block.timestamp) / (endTimestamp() - startTimestamp()) == underlyingAmount // thus, wrappedTokenAmount = underlyingAmount * (endTimestamp() - startTimestamp()) / (endTimestamp() - block.timestamp) wrappedTokenAmount = (underlyingAmount * (_endTimestamp - _startTimestamp)) / (_endTimestamp - block.timestamp); // pretend we have claimed the vested underlying amount claimedUnderlyingAmount[recipient] += wrappedTokenAmount - underlyingAmount; } else { // vest hasn't started yet wrappedTokenAmount = underlyingAmount; } // mint wrapped tokens _mint(recipient, wrappedTokenAmount); /// ------------------------------------------------------------------- /// Effects /// ------------------------------------------------------------------- ERC20 underlyingToken = ERC20(underlying()); underlyingToken.safeTransferFrom( msg.sender, address(this), underlyingAmount ); } /// @notice Allows a holder of the wrapped token to redeem the vested tokens /// @param recipient The address that will receive the vested tokens /// @return redeemedAmount The amount of vested tokens redeemed function redeem(address recipient) external returns (uint256 redeemedAmount) { /// ------------------------------------------------------------------- /// State updates /// ------------------------------------------------------------------- uint256 _claimedUnderlyingAmount = claimedUnderlyingAmount[msg.sender]; redeemedAmount = _getRedeemableAmount( msg.sender, _claimedUnderlyingAmount ); claimedUnderlyingAmount[msg.sender] = _claimedUnderlyingAmount + redeemedAmount; /// ------------------------------------------------------------------- /// Effects /// ------------------------------------------------------------------- if (redeemedAmount > 0) { ERC20 underlyingToken = ERC20(underlying()); underlyingToken.safeTransfer(recipient, redeemedAmount); } } /// @notice The ERC20 transfer function function transfer(address to, uint256 amount) public override returns (bool) { uint256 senderBalance = balanceOf[msg.sender]; uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[ msg.sender ]; balanceOf[msg.sender] = senderBalance - amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv( senderClaimedUnderlyingAmount, amount, senderBalance ); if (claimedUnderlyingAmountToTransfer > 0) { claimedUnderlyingAmount[msg.sender] = senderClaimedUnderlyingAmount - claimedUnderlyingAmountToTransfer; unchecked { claimedUnderlyingAmount[ to ] += claimedUnderlyingAmountToTransfer; } } emit Transfer(msg.sender, to, amount); return true; } /// @notice The ERC20 transferFrom function function transferFrom( address from, address to, uint256 amount ) public override returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; uint256 fromBalance = balanceOf[from]; uint256 fromClaimedUnderlyingAmount = claimedUnderlyingAmount[from]; balanceOf[from] = fromBalance - amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv( fromClaimedUnderlyingAmount, amount, fromBalance ); if (claimedUnderlyingAmountToTransfer > 0) { claimedUnderlyingAmount[from] = fromClaimedUnderlyingAmount - claimedUnderlyingAmountToTransfer; unchecked { claimedUnderlyingAmount[ to ] += claimedUnderlyingAmountToTransfer; } } emit Transfer(from, to, amount); return true; } /// ----------------------------------------------------------------------- /// Getters /// ----------------------------------------------------------------------- /// @notice Computes the amount of vested tokens redeemable by an account /// @param holder The wrapped token holder to query /// @return The amount of vested tokens redeemable function getRedeemableAmount(address holder) external view returns (uint256) { return _getRedeemableAmount(holder, claimedUnderlyingAmount[holder]); } /// ----------------------------------------------------------------------- /// Internal functions /// ----------------------------------------------------------------------- function _getRedeemableAmount( address holder, uint256 holderClaimedUnderlyingAmount ) internal view returns (uint256) { uint256 _startTimestamp = startTimestamp(); uint256 _endTimestamp = endTimestamp(); if (block.timestamp <= _startTimestamp) { // vest hasn't started yet, nothing is vested return 0; } else if (block.timestamp >= _endTimestamp) { // vest is over, everything is vested return balanceOf[holder] - holderClaimedUnderlyingAmount; } else { // middle of vest, compute linear vesting return (balanceOf[holder] * (block.timestamp - _startTimestamp)) / (_endTimestamp - _startTimestamp) - holderClaimedUnderlyingAmount; } } } /// @title VestedERC20Factory /// @author zefram.eth /// @notice Factory for deploying VestedERC20 contracts cheaply contract VestedERC20Factory { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using ClonesWithImmutableArgs for address; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_InvalidTimeRange(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event CreateVestedERC20(VestedERC20 vestedERC20); /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The VestedERC20 used as the template for all clones created VestedERC20 public immutable implementation; constructor(VestedERC20 implementation_) { implementation = implementation_; } /// @notice Creates a VestedERC20 contract /// @dev Uses a modified minimal proxy contract that stores immutable parameters in code and /// passes them in through calldata. See ClonesWithCallData. /// @param name The name of the VestedERC20 token /// @param symbol The symbol of the VestedERC20 token /// @param decimals The number of decimals used by the VestedERC20 token /// @param underlying The ERC20 token that is vested /// @param startTimestamp The start time of the vest, Unix timestamp in seconds /// @param endTimestamp The end time of the vest, must be greater than startTimestamp, Unix timestamp in seconds /// @return vestedERC20 The created VestedERC20 contract function createVestedERC20( bytes32 name, bytes32 symbol, uint8 decimals, address underlying, uint64 startTimestamp, uint64 endTimestamp ) external returns (VestedERC20 vestedERC20) { if (endTimestamp <= startTimestamp) { revert Error_InvalidTimeRange(); } bytes memory data = abi.encodePacked( name, symbol, decimals, underlying, startTimestamp, endTimestamp ); vestedERC20 = VestedERC20(address(implementation).clone(data)); emit CreateVestedERC20(vestedERC20); } }
@notice The ERC20 transfer function Cannot overflow because the sum of all user balances can't exceed the max uint256 value.
function transfer(address to, uint256 amount) public override returns (bool) { uint256 senderBalance = balanceOf[msg.sender]; uint256 senderClaimedUnderlyingAmount = claimedUnderlyingAmount[ msg.sender ]; balanceOf[msg.sender] = senderBalance - amount; unchecked { balanceOf[to] += amount; } uint256 claimedUnderlyingAmountToTransfer = FullMath.mulDiv( senderClaimedUnderlyingAmount, amount, senderBalance ); if (claimedUnderlyingAmountToTransfer > 0) { claimedUnderlyingAmount[msg.sender] = senderClaimedUnderlyingAmount - claimedUnderlyingAmountToTransfer; unchecked { claimedUnderlyingAmount[ to ] += claimedUnderlyingAmountToTransfer; } } emit Transfer(msg.sender, to, amount); return true; }
2,133,681
[ 1, 1986, 4232, 39, 3462, 7412, 445, 14143, 9391, 2724, 326, 2142, 434, 777, 729, 324, 26488, 848, 1404, 9943, 326, 943, 2254, 5034, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 203, 5411, 1071, 203, 5411, 3849, 203, 5411, 1135, 261, 6430, 13, 203, 3639, 288, 203, 5411, 2254, 5034, 5793, 13937, 273, 11013, 951, 63, 3576, 18, 15330, 15533, 203, 5411, 2254, 5034, 5793, 9762, 329, 14655, 6291, 6275, 273, 7516, 329, 14655, 6291, 6275, 63, 203, 7734, 1234, 18, 15330, 203, 5411, 308, 31, 203, 203, 5411, 11013, 951, 63, 3576, 18, 15330, 65, 273, 5793, 13937, 300, 3844, 31, 203, 203, 5411, 22893, 288, 203, 7734, 11013, 951, 63, 869, 65, 1011, 3844, 31, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 7516, 329, 14655, 6291, 6275, 774, 5912, 273, 11692, 10477, 18, 16411, 7244, 12, 203, 7734, 5793, 9762, 329, 14655, 6291, 6275, 16, 203, 7734, 3844, 16, 203, 7734, 5793, 13937, 203, 5411, 11272, 203, 203, 5411, 309, 261, 14784, 329, 14655, 6291, 6275, 774, 5912, 405, 374, 13, 288, 203, 7734, 7516, 329, 14655, 6291, 6275, 63, 3576, 18, 15330, 65, 273, 203, 10792, 5793, 9762, 329, 14655, 6291, 6275, 300, 203, 10792, 7516, 329, 14655, 6291, 6275, 774, 5912, 31, 203, 7734, 22893, 288, 203, 10792, 7516, 329, 14655, 6291, 6275, 63, 203, 13491, 358, 203, 10792, 308, 1011, 7516, 329, 14655, 6291, 6275, 774, 5912, 31, 203, 7734, 289, 203, 5411, 289, 203, 203, 5411, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 3844, 1769, 203, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract LongBar is ERC20("LongBar", "xLONG"){ using SafeMath for uint256; IERC20 public long; constructor(IERC20 _long) public { long = _long; } // Enter the bar. Pay some LONGs. Earn some shares. function enter(uint256 _amount) public { uint256 totalLong = long.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalLong == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalLong); _mint(msg.sender, what); } long.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your LONGs. function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(long.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); long.transfer(msg.sender, what); } }
Enter the bar. Pay some LONGs. Earn some shares.
function enter(uint256 _amount) public { uint256 totalLong = long.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalLong == 0) { _mint(msg.sender, _amount); uint256 what = _amount.mul(totalShares).div(totalLong); _mint(msg.sender, what); } long.transferFrom(msg.sender, address(this), _amount); }
12,903,401
[ 1, 10237, 326, 4653, 18, 13838, 2690, 14011, 87, 18, 512, 1303, 2690, 24123, 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, 6103, 12, 11890, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2254, 5034, 2078, 3708, 273, 1525, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 24051, 273, 2078, 3088, 1283, 5621, 203, 3639, 309, 261, 4963, 24051, 422, 374, 747, 2078, 3708, 422, 374, 13, 288, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 8949, 1769, 203, 5411, 2254, 5034, 4121, 273, 389, 8949, 18, 16411, 12, 4963, 24051, 2934, 2892, 12, 4963, 3708, 1769, 203, 5411, 389, 81, 474, 12, 3576, 18, 15330, 16, 4121, 1769, 203, 3639, 289, 203, 3639, 1525, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 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 ]
./partial_match/3/0x088312248BD02633360658A53a3AeDa5412e3A9D/sources/DataStructures1.sol
Metodo 1 los datos deben ir en orden.
function addToArrOfStructs1(string memory _marca, uint _precio) public { motos.push(Motos(_marca,_precio)); }
16,633,798
[ 1, 12244, 7370, 404, 22148, 19836, 18202, 275, 9482, 570, 4642, 275, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9604, 5715, 951, 3823, 87, 21, 12, 1080, 3778, 389, 3684, 5353, 16, 2254, 389, 4036, 1594, 13, 1071, 288, 203, 3639, 11310, 538, 18, 6206, 12, 49, 12440, 24899, 3684, 5353, 16, 67, 4036, 1594, 10019, 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 ]
pragma solidity 0.6.12; 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 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); } } 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; } } contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "BREE"; string public name = "CBDAO"; uint256 public decimals = 18; uint256 private maxCapSupply = 1e7 * 10**(decimals); // 10 million uint256 _totalSupply = 1530409 * 10 ** (decimals); // 1,530,409 address stakeFarmingContract; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { // mint _totalSupply amount of tokens and send to owner balances[owner] = balances[owner].add(_totalSupply); emit Transfer(address(0),owner, _totalSupply); } // ------------------------------------------------------------------------ // Set the STAKE_FARMING_CONTRACT // @required only owner // ------------------------------------------------------------------------ function SetStakeFarmingContract(address _address) external onlyOwner{ require(_address != address(0), "Invalid address"); stakeFarmingContract = _address; } // ------------------------------------------------------------------------ // Token Minting function // @params _amount expects the amount of tokens to be minted excluding the // required decimals // @params _beneficiary tokens will be sent to _beneficiary // @required only owner OR stakeFarmingContract // ------------------------------------------------------------------------ function MintTokens(uint256 _amount, address _beneficiary) public returns(bool){ require(msg.sender == stakeFarmingContract); require(_beneficiary != address(0), "Invalid address"); require(_totalSupply.add(_amount) <= maxCapSupply, "exceeds max cap supply 10 million"); _totalSupply = _totalSupply.add(_amount); // mint _amount tokens and keep inside contract balances[_beneficiary] = balances[_beneficiary].add(_amount); emit Transfer(address(0),_beneficiary, _amount); return true; } // ------------------------------------------------------------------------ // Burn the `_amount` amount of tokens from the calling `account` // @params _amount the amount of tokens to burn // ------------------------------------------------------------------------ function BurnTokens(uint256 _amount) external { _burn(_amount, msg.sender); } // ------------------------------------------------------------------------ // @dev Internal function that burns an amount of the token from a given account // @param _amount The amount that will be burnt // @param _account The tokens to burn from // ------------------------------------------------------------------------ function _burn(uint256 _amount, address _account) internal { require(balances[_account] >= _amount, "insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** ERC20Interface function's implementation **/ // ------------------------------------------------------------------------ // Get the total supply of the `token` // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to].add(tokens) >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender,to,tokens); return true; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); require(from != address(0), "Invalid address"); require(to != address(0), "Invalid address"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } }
------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "BREE"; string public name = "CBDAO"; uint256 public decimals = 18; address stakeFarmingContract; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; constructor() public { balances[owner] = balances[owner].add(_totalSupply); emit Transfer(address(0),owner, _totalSupply); } function SetStakeFarmingContract(address _address) external onlyOwner{ require(_address != address(0), "Invalid address"); stakeFarmingContract = _address; } function MintTokens(uint256 _amount, address _beneficiary) public returns(bool){ require(msg.sender == stakeFarmingContract); require(_beneficiary != address(0), "Invalid address"); require(_totalSupply.add(_amount) <= maxCapSupply, "exceeds max cap supply 10 million"); _totalSupply = _totalSupply.add(_amount); balances[_beneficiary] = balances[_beneficiary].add(_amount); emit Transfer(address(0),_beneficiary, _amount); return true; } function BurnTokens(uint256 _amount) external { _burn(_amount, msg.sender); } function _burn(uint256 _amount, address _account) internal { require(balances[_account] >= _amount, "insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } function totalSupply() public override view returns (uint256){ return _totalSupply; } function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } function transfer(address to, uint256 tokens) public override returns (bool success) { require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to].add(tokens) >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender,to,tokens); return true; } function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(balances[from] >= tokens); require(from != address(0), "Invalid address"); require(to != address(0), "Invalid address"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; } function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } }
7,415,760
[ 1, 29461, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 3155, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 203, 565, 533, 1071, 3273, 273, 315, 38, 9719, 14432, 203, 203, 203, 565, 533, 1071, 225, 508, 273, 315, 8876, 18485, 14432, 203, 203, 203, 565, 2254, 5034, 1071, 15105, 273, 6549, 31, 203, 203, 203, 203, 203, 203, 203, 565, 1758, 384, 911, 42, 4610, 310, 8924, 31, 203, 203, 203, 377, 203, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 324, 26488, 31, 203, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 203, 377, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 203, 203, 203, 203, 3639, 324, 26488, 63, 8443, 65, 273, 324, 26488, 63, 8443, 8009, 1289, 24899, 4963, 3088, 1283, 1769, 203, 203, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 8443, 16, 389, 4963, 3088, 1283, 1769, 203, 203, 203, 565, 289, 203, 203, 203, 377, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 445, 1000, 510, 911, 42, 4610, 310, 8924, 12, 2867, 389, 2867, 13, 3903, 1338, 5541, 95, 203, 203, 203, 3639, 2583, 24899, 2867, 480, 1758, 12, 20, 3631, 315, 1941, 1758, 8863, 203, 203, 203, 3639, 384, 911, 42, 4610, 310, 8924, 273, 389, 2867, 31, 203, 203, 203, 565, 289, 203, 203, 203, 377, 203, 203, 203, 203, 203, 203, 203, 203, 203, 2 ]
./full_match/4/0xFA3f369c2979bf10841680A3C49F8BD2fC4FD93D/sources/HelloWorld.sol
Store a message in the smart contract Set the message
contract HelloWorld { string storedMessage; pragma solidity ^0.8.4; function set(string memory message) public { storedMessage = message; } function get() public view returns (string memory) { return storedMessage; } }
12,456,678
[ 1, 2257, 279, 883, 316, 326, 13706, 6835, 1000, 326, 883, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 20889, 18071, 288, 203, 565, 533, 4041, 1079, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 444, 12, 1080, 3778, 883, 13, 1071, 288, 203, 3639, 4041, 1079, 273, 883, 31, 203, 565, 289, 203, 203, 565, 445, 336, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 4041, 1079, 31, 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, -100, -100, -100, -100, -100 ]
./full_match/43114/0x0EfC29e196da2e81AFE96eDD041bEdCdF9e74893/sources/contracts/synapse/wrappers/NerveMetaBridgeZap.sol
swap deposit into bridge, gets nUSD
function swapAndRedeem( address to, uint256 chainId, IERC20 token, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external { metaTokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 swappedAmount = metaSwap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); if ( token.allowance(address(this), address(synapseBridge)) < swappedAmount ) { token.safeApprove(address(synapseBridge), MAX_UINT256); } synapseBridge.redeem(to, chainId, token, swappedAmount); }
4,606,615
[ 1, 22270, 443, 1724, 1368, 10105, 16, 5571, 290, 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, 225, 445, 7720, 1876, 426, 24903, 12, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 2687, 548, 16, 203, 565, 467, 654, 39, 3462, 1147, 16, 203, 565, 2254, 28, 1147, 1016, 1265, 16, 203, 565, 2254, 28, 1147, 1016, 774, 16, 203, 565, 2254, 5034, 6633, 16, 203, 565, 2254, 5034, 1131, 40, 93, 16, 203, 565, 2254, 5034, 14096, 203, 225, 262, 3903, 288, 203, 565, 2191, 5157, 63, 2316, 1016, 1265, 8009, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 6633, 1769, 203, 203, 565, 2254, 5034, 7720, 1845, 6275, 273, 2191, 12521, 18, 22270, 12, 203, 1377, 1147, 1016, 1265, 16, 203, 1377, 1147, 1016, 774, 16, 203, 1377, 6633, 16, 203, 1377, 1131, 40, 93, 16, 203, 1377, 14096, 203, 565, 11272, 203, 565, 309, 261, 203, 1377, 1147, 18, 5965, 1359, 12, 2867, 12, 2211, 3631, 1758, 12, 11982, 28933, 13691, 3719, 411, 7720, 1845, 6275, 203, 565, 262, 288, 203, 1377, 1147, 18, 4626, 12053, 537, 12, 2867, 12, 11982, 28933, 13691, 3631, 4552, 67, 57, 3217, 5034, 1769, 203, 565, 289, 203, 565, 6194, 28933, 13691, 18, 266, 24903, 12, 869, 16, 2687, 548, 16, 1147, 16, 7720, 1845, 6275, 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 ]
./partial_match/1/0x8A1D6b7fd5aa061AFe4Ce7F2Aaac0731A2266D41/sources/src/managers/StrategyRegistry.sol
there will be dust left after all vaults sync
function claimWithdrawals(address[] calldata strategies_, uint16a16 dhwIndexes, uint256[] calldata strategyShares) external onlyRole(ROLE_SMART_VAULT_MANAGER, msg.sender) returns (uint256[] memory) { address[] memory assetGroup; uint256[] memory totalWithdrawnAssets; for (uint256 i; i < strategies_.length; ++i) { address strategy = strategies_[i]; if (strategies_[i] == _ghostStrategy) { continue; } if (assetGroup.length == 0) { assetGroup = IStrategy(strategy).assets(); totalWithdrawnAssets = new uint256[](assetGroup.length); } if (strategyShares[i] == 0) { continue; } uint256 dhwIndex = dhwIndexes.get(i); if (dhwIndex == _currentIndexes[strategy]) { revert DhwNotRunYetForIndex(strategy, dhwIndex); } for (uint256 j = 0; j < totalWithdrawnAssets.length; j++) { uint256 withdrawnAssets = _assetsWithdrawn[strategy][dhwIndex][j] * strategyShares[i] / _sharesRedeemed[strategy][dhwIndex]; totalWithdrawnAssets[j] += withdrawnAssets; _assetsNotClaimed[strategy][j] -= withdrawnAssets; } } return totalWithdrawnAssets; }
15,730,805
[ 1, 18664, 903, 506, 302, 641, 2002, 1839, 777, 9229, 87, 3792, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7516, 1190, 9446, 1031, 12, 2867, 8526, 745, 892, 20417, 67, 16, 2254, 2313, 69, 2313, 11007, 91, 8639, 16, 2254, 5034, 8526, 745, 892, 6252, 24051, 13, 203, 3639, 3903, 203, 3639, 1338, 2996, 12, 16256, 67, 7303, 4928, 67, 27722, 2274, 67, 19402, 16, 1234, 18, 15330, 13, 203, 3639, 1135, 261, 11890, 5034, 8526, 3778, 13, 203, 565, 288, 203, 3639, 1758, 8526, 3778, 3310, 1114, 31, 203, 3639, 2254, 5034, 8526, 3778, 2078, 1190, 9446, 82, 10726, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 20417, 27799, 2469, 31, 965, 77, 13, 288, 203, 5411, 1758, 6252, 273, 20417, 67, 63, 77, 15533, 203, 203, 5411, 309, 261, 701, 15127, 67, 63, 77, 65, 422, 389, 75, 2564, 4525, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 9406, 1114, 18, 2469, 422, 374, 13, 288, 203, 7734, 3310, 1114, 273, 467, 4525, 12, 14914, 2934, 9971, 5621, 203, 7734, 2078, 1190, 9446, 82, 10726, 273, 394, 2254, 5034, 8526, 12, 9406, 1114, 18, 2469, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 14914, 24051, 63, 77, 65, 422, 374, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 11007, 91, 1016, 273, 11007, 91, 8639, 18, 588, 12, 77, 1769, 203, 203, 5411, 309, 261, 19153, 91, 1016, 422, 389, 2972, 8639, 63, 14914, 5717, 288, 203, 7734, 15226, 463, 20701, 1248, 1997, 61, 278, 1290, 1016, 12, 14914, 16, 11007, 91, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./interfaces/IStaking.sol"; /** * @title AirSwap Staking: Stake and Unstake Tokens * @notice https://www.airswap.io/ */ contract Staking is IStaking, Ownable { using SafeERC20 for ERC20; using SafeMath for uint256; // Token to be staked ERC20 public immutable token; // Unstaking duration uint256 public duration; // Timelock delay uint256 private minDelay; // Timeunlock timestamp uint256 private timeUnlock; // Mapping of account to stakes mapping(address => Stake) internal stakes; // Mapping of account to proposed delegate mapping(address => address) public proposedDelegates; // Mapping of account to delegate mapping(address => address) public accountDelegates; // Mapping of delegate to account mapping(address => address) public delegateAccounts; // Mapping of timelock ids to used state mapping(bytes32 => bool) private usedIds; // Mapping of ids to timestamps mapping(bytes32 => uint256) private unlockTimestamps; // ERC-20 token properties string public name; string public symbol; /** * @notice Constructor * @param _token address * @param _name string * @param _symbol string * @param _duration uint256 */ constructor( ERC20 _token, string memory _name, string memory _symbol, uint256 _duration, uint256 _minDelay ) { token = _token; name = _name; symbol = _symbol; duration = _duration; minDelay = _minDelay; } /** * @notice Set metadata config * @param _name string * @param _symbol string */ function setMetaData(string memory _name, string memory _symbol) external onlyOwner { name = _name; symbol = _symbol; } /** * @dev Schedules timelock to change duration * @param delay uint256 */ function scheduleDurationChange(uint256 delay) external onlyOwner { require(timeUnlock == 0, "TIMELOCK_ACTIVE"); require(delay >= minDelay, "INVALID_DELAY"); timeUnlock = block.timestamp + delay; emit ScheduleDurationChange(timeUnlock); } /** * @dev Cancels timelock to change duration */ function cancelDurationChange() external onlyOwner { require(timeUnlock > 0, "TIMELOCK_INACTIVE"); delete timeUnlock; emit CancelDurationChange(); } /** * @notice Set unstaking duration * @param _duration uint256 */ function setDuration(uint256 _duration) external onlyOwner { require(_duration != 0, "DURATION_INVALID"); require(timeUnlock > 0, "TIMELOCK_INACTIVE"); require(block.timestamp >= timeUnlock, "TIMELOCKED"); duration = _duration; delete timeUnlock; emit CompleteDurationChange(_duration); } /** * @notice Propose delegate for account * @param delegate address */ function proposeDelegate(address delegate) external { require(accountDelegates[msg.sender] == address(0), "SENDER_HAS_DELEGATE"); require(delegateAccounts[delegate] == address(0), "DELEGATE_IS_TAKEN"); require(stakes[delegate].balance == 0, "DELEGATE_MUST_NOT_BE_STAKED"); proposedDelegates[msg.sender] = delegate; emit ProposeDelegate(delegate, msg.sender); } /** * @notice Set delegate for account * @param account address */ function setDelegate(address account) external { require(proposedDelegates[account] == msg.sender, "MUST_BE_PROPOSED"); require(delegateAccounts[msg.sender] == address(0), "DELEGATE_IS_TAKEN"); require(stakes[msg.sender].balance == 0, "DELEGATE_MUST_NOT_BE_STAKED"); accountDelegates[account] = msg.sender; delegateAccounts[msg.sender] = account; delete proposedDelegates[account]; emit SetDelegate(msg.sender, account); } /** * @notice Unset delegate for account * @param delegate address */ function unsetDelegate(address delegate) external { require(accountDelegates[msg.sender] == delegate, "DELEGATE_NOT_SET"); accountDelegates[msg.sender] = address(0); delegateAccounts[delegate] = address(0); } /** * @notice Stake tokens * @param amount uint256 */ function stake(uint256 amount) external override { if (delegateAccounts[msg.sender] != address(0)) { _stake(delegateAccounts[msg.sender], amount); } else { _stake(msg.sender, amount); } } /** * @notice Unstake tokens * @param amount uint256 */ function unstake(uint256 amount) external override { address account; delegateAccounts[msg.sender] != address(0) ? account = delegateAccounts[msg.sender] : account = msg.sender; _unstake(account, amount); token.transfer(account, amount); emit Transfer(account, address(0), amount); } /** * @notice Receive stakes for an account * @param account address */ function getStakes(address account) external view override returns (Stake memory accountStake) { return stakes[account]; } /** * @notice Total balance of all accounts (ERC-20) */ function totalSupply() external view override returns (uint256) { return token.balanceOf(address(this)); } /** * @notice Balance of an account (ERC-20) */ function balanceOf(address account) external view override returns (uint256 total) { return stakes[account].balance; } /** * @notice Decimals of underlying token (ERC-20) */ function decimals() external view override returns (uint8) { return token.decimals(); } /** * @notice Stake tokens for an account * @param account address * @param amount uint256 */ function stakeFor(address account, uint256 amount) public override { _stake(account, amount); } /** * @notice Available amount for an account * @param account uint256 */ function available(address account) public view override returns (uint256) { Stake storage selected = stakes[account]; uint256 _available = (block.timestamp.sub(selected.timestamp)) .mul(selected.balance) .div(selected.duration); if (_available >= stakes[account].balance) { return stakes[account].balance; } else { return _available; } } /** * @notice Stake tokens for an account * @param account address * @param amount uint256 */ function _stake(address account, uint256 amount) internal { require(amount > 0, "AMOUNT_INVALID"); stakes[account].duration = duration; if (stakes[account].balance == 0) { stakes[account].balance = amount; stakes[account].timestamp = block.timestamp; } else { uint256 nowAvailable = available(account); stakes[account].balance = stakes[account].balance.add(amount); stakes[account].timestamp = block.timestamp.sub( nowAvailable.mul(stakes[account].duration).div(stakes[account].balance) ); } token.safeTransferFrom(msg.sender, address(this), amount); emit Transfer(address(0), account, amount); } /** * @notice Unstake tokens * @param account address * @param amount uint256 */ function _unstake(address account, uint256 amount) internal { Stake storage selected = stakes[account]; require(amount <= available(account), "AMOUNT_EXCEEDS_AVAILABLE"); selected.balance = selected.balance.sub(amount); } }
* @notice Constructor @param _token address @param _name string @param _symbol string @param _duration uint256/
) { token = _token; name = _name; symbol = _symbol; duration = _duration; minDelay = _minDelay; }
12,892,481
[ 1, 6293, 225, 389, 2316, 1758, 225, 389, 529, 533, 225, 389, 7175, 533, 225, 389, 8760, 2254, 5034, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 262, 288, 203, 565, 1147, 273, 389, 2316, 31, 203, 565, 508, 273, 389, 529, 31, 203, 565, 3273, 273, 389, 7175, 31, 203, 565, 3734, 273, 389, 8760, 31, 203, 565, 1131, 6763, 273, 389, 1154, 6763, 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 ]
pragma solidity ^0.4.19; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract CNEinterface { function CNEFallback(address _from, uint _value, uint _code); } contract CNE is ERC20 { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => bool) public blacklist; string public constant name = "CNE"; string public constant symbol = "CNE"; uint public constant decimals = 8; uint256 public totalSupply = 2100000000e8; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); modifier onlyOwner() { require(msg.sender == owner); _; } function CNE () public { owner = msg.sender; balances[owner]= 2100000000e8; Transfer(address(0), owner, 2100000000e8); } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function () public payable { } function balanceOf(address _owner)public view returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256) { return allowed[_owner][_spender]; } function withdraw() onlyOwner public { uint256 etherBalance = this.balance; owner.transfer(etherBalance); } function transfer(address _to, uint _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. if(!isContract(_to)){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else{ balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); CNEinterface receiver = CNEinterface(_to); receiver.CNEFallback(msg.sender, _value, 0); Transfer(msg.sender, _to, _value); return true; } } function transfer(address _to, uint _value,uint _code) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. if(!isContract(_to)){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else{ balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); CNEinterface receiver = CNEinterface(_to); receiver.CNEFallback(msg.sender, _value, _code); Transfer(msg.sender, _to, _value); return true; } } function isContract(address _addr) private returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } }
SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); if(!isContract(_to)){ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } else{ balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); CNEinterface receiver = CNEinterface(_to); receiver.CNEFallback(msg.sender, _value, 0); Transfer(msg.sender, _to, _value); return true; } }
13,659,427
[ 1, 9890, 10477, 18, 1717, 903, 604, 309, 1915, 353, 486, 7304, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7412, 12, 2867, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 3639, 309, 12, 5, 291, 8924, 24899, 869, 3719, 95, 203, 5411, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 5411, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 5411, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 5411, 327, 638, 31, 203, 5411, 289, 203, 3639, 469, 95, 203, 5411, 324, 26488, 63, 3576, 18, 15330, 65, 273, 11013, 951, 12, 3576, 18, 15330, 2934, 1717, 24899, 1132, 1769, 203, 5411, 324, 26488, 63, 67, 869, 65, 273, 11013, 951, 24899, 869, 2934, 1289, 24899, 1132, 1769, 203, 5411, 385, 5407, 5831, 5971, 273, 385, 5407, 5831, 24899, 869, 1769, 203, 5411, 5971, 18, 39, 5407, 12355, 12, 3576, 18, 15330, 16, 389, 1132, 16, 374, 1769, 203, 5411, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 5411, 327, 638, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "../core/Common.sol"; import "../oracle/OracleFacade.sol"; /** * @title Main insurance contract * @dev Implement main contract for Insurance. contract between insurance and farmers is materialized in here * * @notice inhertit {Common} contract */ contract Insurance is Common { /// @dev Emitted when a `contract` is activated by an `insurer` for a given `season` + `region` + `farmID` event InsuranceActivated( uint16 indexed season, bytes32 region, bytes32 farmID, address indexed insurer, bytes32 key ); /// @dev Emitted when a `contract` is submitted by an `farmer` for a given `season` + `region` + `farmID` event InsuranceRequested( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, uint256 fee, address indexed farmer, bytes32 key ); /// @dev Emitted when a `contract` is validated by a `government` for a given `season` + `region` + `farmID` event InsuranceValidated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 totalStaked, address indexed government, bytes32 key ); /// @dev Emitted when a `contract` is closed without any compensation event InsuranceClosed( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity, bytes32 key ); /// @dev Emitted when a `contract` is closed with any compensation event InsuranceCompensated( uint16 indexed season, bytes32 region, bytes32 farmID, uint256 size, address indexed farmer, address indexed insurer, address government, uint256 totalStaked, uint256 compensation, Severity severity, bytes32 key ); /// @dev Emitted when an `insurer` withdraws `amount` from the contract. remaining contract balance is `balance` event WithdrawInsurer( address indexed insurer, uint256 amount, uint256 balance ); /** * @dev transition state of a contract * * a contract must be in init state (DEFAULT) * a contract transition to (REGISTERED) once a farmer registers himself * a contract transition to (VALIDATED) once a government employee validates the demand * a contract transition to (INSURED) once an insurer approves the contract * a contract transition to (CLOSED) once a season is closed without any drought, hence there are no compensations * a contract transition to (COMPENSATED) once a season is closed and there were drought, hence there are compensations */ enum ContractState { DEFAULT, REGISTERED, VALIDATED, INSURED, CLOSED, COMPENSATED } struct Contract { bytes32 key; bytes32 farmID; ContractState state; address farmer; address government; address insurer; uint256 size; bytes32 region; uint16 season; uint256 totalStaked; uint256 compensation; uint256 changeGovernment; Severity severity; } /// @dev OracleFacade used to get the status of a season(open/closed) and Severity for a given season + region OracleFacade private oracleFacade; /// @dev a contract is a unique combination between season,region,farmID mapping(bytes32 => Contract) private contracts; /// @dev contracts that must be treated by season,region mapping(bytes32 => bytes32[]) private openContracts; /// @dev contracts that have already been closed by season,region mapping(bytes32 => bytes32[]) private closedContracts; uint256 public constant KEEPER_FEE = 0.01 ether; /// @dev needed to track worst case scenario -> must have at anytime money to pay for severity/D4 : 2.5*PERMIUM_PER_HA*totalsize uint256 public totalOpenSize; /// @dev needed to track amount to be paid for keepers uint256 public totalOpenContracts; /** * @dev rules to calculate the compensation * * D1 gives 0.5 times the premium * D2 gives 1 times the premium * D3 gives 2 times the premium * D4 gives 2.5 times the premium */ mapping(Severity => uint8) private rules; /// @dev premium is 0.15ETH/HA uint256 public constant PERMIUM_PER_HA = 150000000 gwei; /// @dev used for calculation (farmer must stake half of premium. Same for government) uint256 public constant HALF_PERMIUM_PER_HA = 75000000 gwei; /** * @dev Initialize `rules` for compensation. Also setup `gatekeeer` and `oracleFacade` * */ constructor(address _gatekeeper, address _oracleFacade) Common(_gatekeeper) { rules[Severity.D0] = 0; rules[Severity.D1] = 5; rules[Severity.D2] = 10; rules[Severity.D3] = 20; rules[Severity.D4] = 25; oracleFacade = OracleFacade(_oracleFacade); } /// @dev modifier to check that at any time there will be enough balance in the contract modifier minimumCovered() { _; require( address(this).balance >= minimumAmount(), "Not enough balance staked in the contract" ); } /// @dev season must be closed in order to check compensations modifier seasonClosed(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.CLOSED, "Season must be closed." ); _; } /// @dev season must be open in order to receive insurance requests modifier seasonOpen(uint16 season) { require( oracleFacade.getSeasonState(season) == SeasonState.OPEN, "Season must be open." ); _; } /** * @dev retrieve contract data part1 * @param _key keecak combination of season, region & farmID * * @return key unique id of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContract1(bytes32 _key) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { Contract memory _contract = contracts[_key]; key = _contract.key; farmID = _contract.farmID; state = _contract.state; farmer = _contract.farmer; government = _contract.government; insurer = _contract.insurer; size = _contract.size; } /** * @dev retrieve contract data part2 * @param _key keecak combination of season, region & farmID * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity fetched from oracleFacade when the contract is closed */ function getContract2(bytes32 _key) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { Contract memory _contract = contracts[_key]; region = _contract.region; season = _contract.season; totalStaked = _contract.totalStaked; compensation = _contract.compensation; changeGovernment = _contract.changeGovernment; severity = _contract.severity; } /** * @dev retrieve contract data (1st part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return key unique ID of the contract * @return farmID unique ID of a farm * @return state of the contract * @return farmer address * @return government address * @return insurer address * @return size number of HA of a farmer (minimum: 1 HA) */ function getContractData1( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 key, bytes32 farmID, ContractState state, address farmer, address government, address insurer, uint256 size ) { (key, farmID, state, farmer, government, insurer, size) = getContract1( getContractKey(_season, _region, _farmID) ); } /** * @dev retrieve contract data (2nd part) * @param _season farming season(year) * @param _region region ID * @param _farmID unique ID of a farm * * @return region ID of a region * @return season (year) * @return totalStaked eth that were taked in this contract * @return compensation for this contract * @return changeGovernment money returned to government * @return severity Drought severity when the contract is closed */ function getContractData2( uint16 _season, bytes32 _region, bytes32 _farmID ) public view returns ( bytes32 region, uint16 season, uint256 totalStaked, uint256 compensation, uint256 changeGovernment, Severity severity ) { bytes32 _key = getContractKey(_season, _region, _farmID); ( region, season, totalStaked, compensation, changeGovernment, severity ) = getContract2(_key); } /** * @dev get number of closed contracts for a given key * * @param key keccak256 of season + region * @return number of closed contracts * */ function getNumberClosedContractsByKey(bytes32 key) public view returns (uint256) { return closedContracts[key].length; } /** * @dev get number of closed contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of closed contracts * */ function getNumberClosedContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberClosedContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific closed contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getClosedContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(closedContracts[key].length > index, "Out of bounds access."); return closedContracts[key][index]; } /** * @dev get a specific closed contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getClosedContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getClosedContractsAtByKey( getSeasonRegionKey(season, region), index ); } /** * @dev calculate contract key * * @param season season (year) * @param region region id * @param farmID farm id * @return key (hash value of the 3 parameters) * */ function getContractKey( uint16 season, bytes32 region, bytes32 farmID ) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region, farmID)); } /** * @dev calculate key of `season`, `region` * * @param season season (year) * @param region region id * @return key (hash value of the 2 parameters) * */ function getSeasonRegionKey(uint16 season, bytes32 region) public pure returns (bytes32) { return keccak256(abi.encodePacked(season, region)); } /** * @dev get number of open contracts for a given key * * @param key keccak256 of season + region * @return number of open contracts * */ function getNumberOpenContractsByKey(bytes32 key) public view returns (uint256) { return openContracts[key].length; } /** * @dev get number of open contracts for a given season and region * * @param season id of a season (year) * @param region id of region * @return number of open contracts * */ function getNumberOpenContracts(uint16 season, bytes32 region) public view returns (uint256) { return getNumberOpenContractsByKey(getSeasonRegionKey(season, region)); } /** * @dev get a specific open contract * * @param key key keccak256 of season + region * @param index position in the array * @return key of a contract * */ function getOpenContractsAtByKey(bytes32 key, uint256 index) public view returns (bytes32) { require(openContracts[key].length > index, "Out of bounds access."); return openContracts[key][index]; } /** * @dev get a specific open contract * * @param season id of a season (year) * @param region id of region * @param index position in the array * @return key of a contract * */ function getOpenContractsAt( uint16 season, bytes32 region, uint256 index ) public view returns (bytes32) { return getOpenContractsAtByKey(getSeasonRegionKey(season, region), index); } /** * @dev insure a request * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceActivated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by insurer * - Check must exist * - Season must be open * - contract must be in VALIDATED state * - Must be enough eth staked within the contract after the operation * @notice call nonReentrant to check against Reentrancy */ function activate( uint16 season, bytes32 region, bytes32 farmID ) external onlyActive onlyInsurer seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.VALIDATED, "Contract must be in validated state" ); _contract.state = ContractState.INSURED; _contract.insurer = msg.sender; contracts[key] = _contract; emit InsuranceActivated(season, region, farmID, msg.sender, key); } /** * @dev calculate at anytime the minimum liquidity that must be locked within the contract * * @return ammount * * Basically , always enough money to pay keepers and compensation in worst case scenarios */ function minimumAmount() public view returns (uint256) { return (KEEPER_FEE * totalOpenContracts) + (PERMIUM_PER_HA * totalOpenSize * rules[Severity.D4]) / 10; } /** * @dev submission of an insurance request by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * @param size number of HA of a farmer (minimum: 1 HA) * * @return key key of the contract * Emits a {InsuranceRequested} event. * * Requirements: * - contract is Active (circuit-breaker) * - Can only be called by farmer * - Check non duplicate * - Seasonmust be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function register( uint16 season, bytes32 region, bytes32 farmID, uint256 size ) external payable onlyActive onlyFarmer seasonOpen(season) nonReentrant minimumCovered returns (bytes32) { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); require(contracts[key].key == 0x0, "Duplicate"); uint256 fee = HALF_PERMIUM_PER_HA * size; require(msg.value >= fee, "Not enough money to pay for premium"); Contract memory _contract; _contract.key = key; _contract.farmID = farmID; _contract.state = ContractState.REGISTERED; _contract.farmer = msg.sender; _contract.size = size; _contract.region = region; _contract.season = season; _contract.totalStaked = fee; contracts[key] = _contract; openContracts[getSeasonRegionKey(season, region)].push(key); totalOpenSize += size; totalOpenContracts++; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceRequested( season, region, farmID, size, fee, msg.sender, key ); return key; } /** * @dev validate a request done by a farmer * @param season farming season(year) * @param region region ID * @param farmID unique ID of a farm * * Emits a {InsuranceValidated} event. * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by government * - Check contract must exist * - Season must be open * - Sender must pay for premium * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function validate( uint16 season, bytes32 region, bytes32 farmID ) external payable onlyActive onlyGovernment seasonOpen(season) nonReentrant minimumCovered { // Generate a unique key for storing the request bytes32 key = getContractKey(season, region, farmID); Contract memory _contract = contracts[key]; require(_contract.farmID == farmID, "Contract do not exist"); require( _contract.state == ContractState.REGISTERED, "Contract must be in registered state" ); uint256 fee = HALF_PERMIUM_PER_HA * _contract.size; require(msg.value >= fee, "Not enough money to pay for premium"); _contract.state = ContractState.VALIDATED; _contract.government = msg.sender; _contract.totalStaked += fee; contracts[key] = _contract; // return change if (msg.value > fee) { (bool success, ) = msg.sender.call{value: msg.value - fee}(""); require(success, "Transfer failed."); } emit InsuranceValidated( season, region, farmID, _contract.totalStaked, msg.sender, key ); } /** * @dev process an insurance file. triggered by a `keeper` * @dev as a combination of `season`,`region` can have several open insurances files, a keeper will have to loop over this function until there are no more open insurances files. looping is done offchain rather than onchain in order to avoid any out of gas exception * @param season farming season(year) * @param region region ID * * Emits a {InsuranceClosed} event in case an insurance file has been closed without any compensation (e.g.: Drought severity <= D1) or returned back becase government has not staked 1/2 of the premium * Emits a {InsuranceCompensated} event in case an insurance file has been processed with compensation (e.g.: Drought severity >= D2) * * Requirements: * - Contract is active (circuit-breaker) * - Can only be called by keeper * - Check contract must exist * - Season must be closed * - Must be open contracts to process * - Must be enough eth staked within the contract * @notice call nonReentrant to check against Reentrancy */ function process(uint16 season, bytes32 region) external onlyActive onlyKeeper seasonClosed(season) nonReentrant minimumCovered { bytes32 seasonRegionKey = getSeasonRegionKey(season, region); bytes32[] memory _openContracts = openContracts[seasonRegionKey]; require( _openContracts.length > 0, "No open insurance contracts to process for this season,region" ); Severity severity = oracleFacade.getRegionSeverity(season, region); uint256 numberSubmissions = oracleFacade.getSubmissionTotal( season, region ); require( !((numberSubmissions > 0) && (severity == Severity.D)), "Severity has not been aggregated yet" ); // get last element bytes32 key = _openContracts[_openContracts.length - 1]; Contract memory _contract = contracts[key]; _contract.severity = severity; Contract memory newContract = _process(_contract); // Update internal state openContracts[seasonRegionKey].pop(); closedContracts[seasonRegionKey].push(key); contracts[key] = newContract; totalOpenSize -= newContract.size; totalOpenContracts--; // pay back if (newContract.compensation > 0) { _deposit(newContract.farmer, newContract.compensation); } if (newContract.changeGovernment > 0) { _deposit(newContract.government, newContract.changeGovernment); } // pay keeper for its work _deposit(msg.sender, KEEPER_FEE); // emit events if (newContract.state == ContractState.COMPENSATED) { emit InsuranceCompensated( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.severity, newContract.key ); } else { emit InsuranceClosed( newContract.season, newContract.region, newContract.farmID, newContract.size, newContract.farmer, newContract.insurer, newContract.government, newContract.totalStaked, newContract.compensation, newContract.changeGovernment, newContract.severity, newContract.key ); } } /** * @dev private function to calculate the new version of the insurance contract after processing * @param _contract current contract before processing * @return newContract new contract after processing * */ function _process(Contract memory _contract) private view returns (Contract memory newContract) { bool isCompensated = false; newContract = _contract; if (newContract.state == ContractState.INSURED) { if (newContract.severity == Severity.D0) { // no compensation if D0 newContract.compensation = 0; newContract.changeGovernment = 0; } else if (newContract.severity == Severity.D) { // if season closed but oracles didn't do their job by providing data then return the change newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } else { isCompensated = true; // calculate compensation newContract.compensation = (rules[newContract.severity] * newContract.totalStaked) / 10; newContract.changeGovernment = 0; } } else if (newContract.state == ContractState.REGISTERED) { // return money back if season closed validation before approval of government newContract.compensation = newContract.totalStaked; } else if (newContract.state == ContractState.VALIDATED) { newContract.compensation = newContract.totalStaked / 2; newContract.changeGovernment = newContract.totalStaked / 2; } //Update contract state if (isCompensated) { newContract.state = ContractState.COMPENSATED; } else { newContract.state = ContractState.CLOSED; } } /** * @dev an insurer can withdraw any excess of liquidity * @param amount to be withdrawed * * Emits a {WithdrawInsurer} event. * * Requirements: * - Can only be called by insurer * - Check non duplicate * - Must be enough eth staked within the contract after operation * @notice call nonReentrant to check against Reentrancy */ function withdrawInsurer(uint256 amount) external onlyInsurer nonReentrant minimumCovered { require( address(this).balance >= amount, "Not enough balance in the contract" ); (bool success, ) = msg.sender.call{value: amount}(""); require(success, "Transfer failed."); emit WithdrawInsurer(msg.sender, amount, address(this).balance); } /** * @dev check anytime amount that can be withdrawed by insurer * @return amount to be withdrawed * * @notice call nonReentrant to check against Reentrancy */ function withdrawableInsurer() external view returns (uint256) { uint256 minimum = minimumAmount(); if (address(this).balance >= minimum) { return address(this).balance - minimum; } else { return 0; } } /** * @dev function to receive ETH in order to pay keepers and oracles * * Emits a {ReceivedETH} event. * * Requirements: * - Contract mus be active (circuit-breaker) * - the caller must be insurer */ receive() external payable onlyActive onlyInsurer { emit ReceivedETH(msg.value, address(this).balance, msg.sender); } }
* @dev calculate at anytime the minimum liquidity that must be locked within the contract @return ammount Basically , always enough money to pay keepers and compensation in worst case scenarios/
function minimumAmount() public view returns (uint256) { return (KEEPER_FEE * totalOpenContracts) + (PERMIUM_PER_HA * totalOpenSize * rules[Severity.D4]) / 10; }
13,043,466
[ 1, 11162, 622, 1281, 957, 326, 5224, 4501, 372, 24237, 716, 1297, 506, 8586, 3470, 326, 6835, 327, 2125, 4778, 7651, 1230, 269, 3712, 7304, 15601, 358, 8843, 3455, 414, 471, 1161, 25159, 316, 22952, 648, 22456, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5224, 6275, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 203, 5411, 261, 6859, 41, 3194, 67, 8090, 41, 380, 2078, 3678, 20723, 13, 397, 203, 5411, 261, 3194, 7492, 2799, 67, 3194, 67, 19191, 380, 2078, 3678, 1225, 380, 2931, 63, 21630, 18, 40, 24, 5717, 342, 203, 5411, 1728, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-02 */ // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity 0.8.6; pragma abicoder v2; // solhint-disable-line /** * @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 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); } } } } /** * @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance * for future withdrawal instead. */ abstract contract SendValueWithFallbackWithdraw is ReentrancyGuard { using Address for address payable; mapping(address => uint256) private pendingWithdrawals; event WithdrawPending(address indexed user, uint256 amount); event Withdrawal(address indexed user, uint256 amount); /** * @notice Returns how much funds are available for manual withdraw due to failed transfers. */ function getPendingWithdrawal(address user) public view returns (uint256) { return pendingWithdrawals[user]; } /** * @notice Allows a user to manually withdraw funds which originally failed to transfer to themselves. */ function withdraw() public { withdrawFor(payable(msg.sender)); } /** * @notice Allows anyone to manually trigger a withdrawal of funds which originally failed to transfer for a user. */ function withdrawFor(address payable user) public nonReentrant { uint256 amount = pendingWithdrawals[user]; require(amount > 0, "No funds are pending withdrawal"); pendingWithdrawals[user] = 0; user.sendValue(amount); emit Withdrawal(user, amount); } /** * @dev Attempt to send a user ETH with a reasonably low gas limit of 20k, * which is enough to send to contracts as well. */ function _sendValueWithFallbackWithdrawWithLowGasLimit(address user, uint256 amount) internal { _sendValueWithFallbackWithdraw(user, amount, 20000); } /** * @dev Attempt to send a user or contract ETH with a moderate gas limit of 90k, * which is enough for a 5-way split. */ function _sendValueWithFallbackWithdrawWithMediumGasLimit(address user, uint256 amount) internal { _sendValueWithFallbackWithdraw(user, amount, 210000); } /** * @dev Attempt to send a user or contract ETH and if it fails store the amount owned for later withdrawal. */ function _sendValueWithFallbackWithdraw( address user, uint256 amount, uint256 gasLimit ) private { if (amount == 0) { return; } // Cap the gas to prevent consuming all available gas to block a tx from completing successfully // solhint-disable-next-line avoid-low-level-calls (bool success, ) = payable(user).call{ value: amount, gas: gasLimit }(""); if (!success) { // Record failed sends for a withdrawal later // Transfers could fail if sent to a multisig with non-trivial receiver logic // solhint-disable-next-line reentrancy pendingWithdrawals[user] = pendingWithdrawals[user] + amount; emit WithdrawPending(user, amount); } } } interface ICAAsset { function ownerOf(uint256 _tokenId) external view returns (address _owner); function exists(uint256 _tokenId) external view returns (bool _exists); function transferFrom(address _from, address _to, uint256 _tokenId) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function safeTransferFrom(address _from , address _to, uint256 _tokenId, bytes memory _data) external; function editionOfTokenId(uint256 _tokenId) external view returns (uint256 tokenId); function artistCommission(uint256 _tokenId) external view returns (address _artistAccount, uint256 _artistCommission); function editionOptionalCommission(uint256 _tokenId) external view returns (uint256 _rate, address _recipient); function mint(address _to, uint256 _editionNumber) external returns (uint256); function approve(address _to, uint256 _tokenId) external; function createActiveEdition( uint256 _editionNumber, bytes32 _editionData, uint256 _editionType, uint256 _startDate, uint256 _endDate, address _artistAccount, uint256 _artistCommission, uint256 _priceInWei, string memory _tokenUri, uint256 _totalAvailable ) external returns (bool); function artistsEditions(address _artistsAccount) external returns (uint256[] memory _editionNumbers); function totalAvailableEdition(uint256 _editionNumber) external returns (uint256); function highestEditionNumber() external returns (uint256); function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient) external; function updateStartDate(uint256 _editionNumber, uint256 _startDate) external; function updateEndDate(uint256 _editionNumber, uint256 _endDate) external; function updateEditionType(uint256 _editionNumber, uint256 _editionType) external; } /** * @dev Constant values shared across mixins. */ abstract contract Constants { uint32 internal constant BASIS_POINTS = 10000; } /** * @notice A mixin to distribute funds when an NFT is sold. */ abstract contract NFTMarketFees is Constants, SendValueWithFallbackWithdraw { event MarketFeesUpdated( uint32 caPoints, uint32 artistPoints, uint32 sellerPoints, uint32 auctionAwardPoints, uint32 sharePoints ); ICAAsset immutable caAsset; uint32 private caPoints; uint32 private sharePoints; uint32 private artistPoints; uint32 private sellerPoints; uint32 private auctionAwardPoints; uint256 public withdrawThreshold; address payable private treasury; mapping(address => uint256) public awards; mapping(uint256 => bool) private nftContractToTokenIdToFirstSaleCompleted; event AuctionAwardUpdated(uint256 indexed auctionId, address indexed bidder, uint256 award); event ShareAwardUpdated(address indexed share, uint256 award); /** * @dev Called once after the initial deployment to set the CART treasury address. */ constructor( ICAAsset _caAsset, address payable _treasury) { require(_treasury != address(0), "NFTMarketFees: Address not zero"); caAsset = _caAsset; treasury = _treasury; caPoints = 150; sharePoints = 100; artistPoints = 1000; sellerPoints = 8250; auctionAwardPoints = 500; withdrawThreshold = 1 ether; } function setCATreasury(address payable _treasury) external { require(_treasury != msg.sender, "NFTMarketFees: no permission"); require(_treasury != address(0), "NFTMarketFees: Address not zero"); treasury = _treasury; } /** * @notice Returns the address of the CART treasury. */ function getCATreasury() public view returns (address payable) { return treasury; } /** * @notice Returns true if the given NFT has not been sold in this market previously and is being sold by the creator. */ function getIsPrimary(uint256 tokenId) public view returns (bool) { return !nftContractToTokenIdToFirstSaleCompleted[tokenId]; } function getArtist(uint256 tokenId) public view returns (address artist) { uint256 editionNumber = caAsset.editionOfTokenId(tokenId); (artist,) = caAsset.artistCommission(editionNumber); } /** * @notice Returns how funds will be distributed for a sale at the given price point. * @dev This could be used to present exact fee distributing on listing or before a bid is placed. */ function getFees(uint tokenId, uint256 price) public view returns ( uint256 caFee, uint256 artistFee, uint256 sellerFee, uint256 auctionFee, uint256 shareFee ) { sellerFee = sellerPoints * price / BASIS_POINTS; // 首次拍卖的时候,作家即卖家,联名者需参与分成 if (!nftContractToTokenIdToFirstSaleCompleted[tokenId]) { caFee = (caPoints + artistPoints) * price / BASIS_POINTS; artistFee = sellerFee; sellerFee = 0; } else { caFee = caPoints * price / BASIS_POINTS; artistFee = artistPoints * price / BASIS_POINTS; } auctionFee = auctionAwardPoints * price / BASIS_POINTS; shareFee = sharePoints * price / BASIS_POINTS; } function withdrawFunds(address to) external { require(awards[msg.sender] >= withdrawThreshold, "NFTMarketFees: under withdrawThreshold"); uint wdAmount= awards[msg.sender]; awards[msg.sender] = 0; _sendValueWithFallbackWithdrawWithMediumGasLimit(to, wdAmount); } function _distributeBidFunds( uint256 lastPrice, uint256 auctionId, uint256 price, address bidder ) internal { uint award = auctionAwardPoints * (price - lastPrice) / BASIS_POINTS; awards[bidder] += award; emit AuctionAwardUpdated(auctionId, bidder, award); } /** * @dev Distributes funds to foundation, creator, and NFT owner after a sale. */ function _distributeFunds( uint256 tokenId, address seller, address shareUser, uint256 price ) internal { (uint caFee, uint artistFee, uint sellerFee, ,uint shareFee) = getFees(tokenId, price); if (shareUser == address(0)) { _sendValueWithFallbackWithdrawWithLowGasLimit(treasury, caFee + shareFee); } else { _sendValueWithFallbackWithdrawWithLowGasLimit(treasury, caFee); awards[shareUser] += shareFee; emit ShareAwardUpdated(shareUser, shareFee); } uint256 editionNumber = caAsset.editionOfTokenId(tokenId); (address artist, uint256 artistRate) = caAsset.artistCommission(editionNumber); (uint256 optionalRate, address optionalRecipient) = caAsset.editionOptionalCommission(editionNumber); if (optionalRecipient == address(0)) { if (artist == seller) { _sendValueWithFallbackWithdrawWithMediumGasLimit(seller, artistFee + sellerFee); } else { _sendValueWithFallbackWithdrawWithMediumGasLimit(seller, sellerFee); _sendValueWithFallbackWithdrawWithMediumGasLimit(artist, artistFee); } } else { uint optionalFee = artistFee * optionalRate / (optionalRate + artistRate); if (optionalFee > 0) { _sendValueWithFallbackWithdrawWithMediumGasLimit(optionalRecipient, optionalFee); } if (artist == seller) { _sendValueWithFallbackWithdrawWithMediumGasLimit(seller, artistFee + sellerFee - optionalFee); } else { _sendValueWithFallbackWithdrawWithMediumGasLimit(seller, sellerFee); _sendValueWithFallbackWithdrawWithMediumGasLimit(artist, artistFee - optionalFee); } } // Anytime fees are distributed that indicates the first sale is complete, // which will not change state during a secondary sale. // This must come after the `getFees` call above as this state is considered in the function. nftContractToTokenIdToFirstSaleCompleted[tokenId] = true; } /** * @notice Returns the current fee configuration in basis points. */ function getFeeConfig() public view returns ( uint32 , uint32 , uint32 , uint32 , uint32) { return (caPoints, artistPoints, sellerPoints, auctionAwardPoints, sharePoints); } /** * @notice Allows CA to change the market fees. */ function _updateMarketFees( uint32 _caPoints, uint32 _artistPoints, uint32 _sellerPoints, uint32 _auctionAwardPoints, uint32 _sharePoints ) internal { require(_caPoints + _artistPoints + _sellerPoints + _auctionAwardPoints + _sharePoints < BASIS_POINTS, "NFTMarketFees: Fees >= 100%"); caPoints = caPoints; artistPoints = _artistPoints; sellerPoints = _sellerPoints; auctionAwardPoints = _auctionAwardPoints; sharePoints = _sharePoints; emit MarketFeesUpdated( _caPoints, _artistPoints, _sellerPoints, _auctionAwardPoints, _sharePoints ); } } /** * @notice An abstraction layer for auctions. * @dev This contract can be expanded with reusable calls and data as more auction types are added. */ abstract contract NFTMarketAuction { /** * @dev A global id for auctions of any type. */ uint256 private nextAuctionId = 1; function _getNextAndIncrementAuctionId() internal returns (uint256) { return nextAuctionId++; } } /** * @notice Interface for OperatorRole which wraps a role from * OpenZeppelin's AccessControl for easy integration. */ interface IAccessControl { function isCAAdmin(address _operator) external view returns (bool); function hasRole(address _operator, uint8 _role) external view returns (bool); function canPlayRole(address _operator, uint8 _role) external view returns (bool); } /** * @notice Manages a reserve price countdown auction for NFTs. */ abstract contract NFTMarketReserveAuction is Constants, ReentrancyGuard, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction { struct ReserveAuction { uint256 tokenId; address seller; uint32 duration; uint32 extensionDuration; uint32 endTime; address bidder; uint256 amount; address shareUser; } mapping(uint256 => uint256) private nftTokenIdToAuctionId; mapping(uint256 => ReserveAuction) private auctionIdToAuction; IAccessControl public immutable accessControl; uint32 private _minPercentIncrementInBasisPoints; uint32 private _duration; // Cap the max duration so that overflows will not occur uint32 private constant MAX_MAX_DURATION = 1000 days; uint32 private constant EXTENSION_DURATION = 15 minutes; event ReserveAuctionConfigUpdated( uint32 minPercentIncrementInBasisPoints, uint256 maxBidIncrementRequirement, uint256 duration, uint256 extensionDuration, uint256 goLiveDate ); event ReserveAuctionCreated( address indexed seller, uint256 indexed tokenId, uint256 indexed auctionId, uint256 duration, uint256 extensionDuration, uint256 reservePrice ); event ReserveAuctionUpdated(uint256 indexed auctionId, uint256 reservePrice); event ReserveAuctionCanceled(uint256 indexed auctionId); event ReserveAuctionBidPlaced(uint256 indexed auctionId, address indexed bidder, uint256 amount, uint256 endTime); event ReserveAuctionFinalized( uint256 indexed auctionId, address indexed seller, address indexed bidder, uint256 tokenId, uint256 amount ); event ReserveAuctionCanceledByAdmin(uint256 indexed auctionId, string reason); event ReserveAuctionSellerMigrated( uint256 indexed auctionId, address indexed originalSellerAddress, address indexed newSellerAddress ); modifier onlyValidAuctionConfig(uint256 reservePrice) { require(reservePrice > 0, "NFTMarketReserveAuction: Reserve price must be at least 1 wei"); _; } modifier onlyCAAdmin(address user) { require(accessControl.isCAAdmin(user), "CAAdminRole: caller does not have the Admin role"); _; } constructor(IAccessControl access) { _duration = 24 hours; // A sensible default value accessControl = access; _minPercentIncrementInBasisPoints = 1000; } /** * @notice Returns auction details for a given auctionId. */ function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; } /** * @notice Returns the auctionId for a given NFT, or 0 if no auction is found. * @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization. */ function getReserveAuctionIdFor(uint256 tokenId) public view returns (uint256) { return nftTokenIdToAuctionId[tokenId]; } /** * @dev Returns the seller that put a given NFT into escrow, * or bubbles the call up to check the current owner if the NFT is not currently in escrow. */ function getSellerFor(uint256 tokenId) internal view virtual returns (address) { address seller = auctionIdToAuction[nftTokenIdToAuctionId[tokenId]].seller; if (seller == address(0)) { return caAsset.ownerOf(tokenId); } return seller; } /** * @notice Returns the current configuration for reserve auctions. */ function getReserveAuctionConfig() public view returns (uint256 minPercentIncrementInBasisPoints, uint256 duration) { minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints; duration = _duration; } function _updateReserveAuctionConfig(uint32 minPercentIncrementInBasisPoints, uint32 duration) internal { require(minPercentIncrementInBasisPoints <= BASIS_POINTS, "NFTMarketReserveAuction: Min increment must be <= 100%"); // Cap the max duration so that overflows will not occur require(duration <= MAX_MAX_DURATION, "NFTMarketReserveAuction: Duration must be <= 1000 days"); require(duration >= EXTENSION_DURATION, "NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION"); _minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints; _duration = duration; // We continue to emit unused configuration variables to simplify the subgraph integration. emit ReserveAuctionConfigUpdated(minPercentIncrementInBasisPoints, 0, duration, EXTENSION_DURATION, 0); } /** * @notice Creates an auction for the given NFT. * The NFT is held in escrow until the auction is finalized or canceled. */ function createReserveAuction( uint256 tokenId, address seller, uint256 reservePrice ) public onlyValidAuctionConfig(reservePrice) nonReentrant { // If an auction is already in progress then the NFT would be in escrow and the modifier would have failed uint256 auctionId = _getNextAndIncrementAuctionId(); nftTokenIdToAuctionId[tokenId] = auctionId; auctionIdToAuction[auctionId] = ReserveAuction( tokenId, seller, _duration, EXTENSION_DURATION, 0, // endTime is only known once the reserve price is met address(0), // bidder is only known once a bid has been placed reservePrice, address(0) ); caAsset.transferFrom(msg.sender, address(this), tokenId); emit ReserveAuctionCreated( seller, tokenId, auctionId, _duration, EXTENSION_DURATION, reservePrice ); } /** * @notice If an auction has been created but has not yet received bids, the configuration * such as the reservePrice may be changed by the seller. */ function updateReserveAuction(uint256 auctionId, uint256 reservePrice) public onlyValidAuctionConfig(reservePrice) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); auction.amount = reservePrice; emit ReserveAuctionUpdated(auctionId, reservePrice); } /** * @notice If an auction has been created but has not yet received bids, it may be canceled by the seller. * The NFT is returned to the seller from escrow. */ function cancelReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); delete nftTokenIdToAuctionId[auction.tokenId]; delete auctionIdToAuction[auctionId]; caAsset.transferFrom(address(this), auction.seller, auction.tokenId); emit ReserveAuctionCanceled(auctionId); } /** * @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`. * If this is the first bid on the auction, the countdown will begin. * If there is already an outstanding bid, the previous bidder will be refunded at this time * and if the bid is placed in the final moments of the auction, the countdown may be extended. */ function placeBid(uint256 auctionId, address shareUser) public payable nonReentrant { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.amount != 0, "NFTMarketReserveAuction: Auction not found"); if (auction.endTime == 0) { // If this is the first bid, ensure it's >= the reserve price require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price"); } else { // If this bid outbids another, confirm that the bid is at least x% greater than the last require(auction.endTime >= block.timestamp, "NFTMarketReserveAuction: Auction is over"); require(auction.bidder != msg.sender, "NFTMarketReserveAuction: You already have an outstanding bid"); uint256 minAmount = _getMinBidAmountForReserveAuction(auction.amount); require(msg.value >= minAmount, "NFTMarketReserveAuction: Bid amount too low"); } if (auction.endTime == 0) { auction.amount = msg.value; auction.bidder = msg.sender; // On the first bid, the endTime is now + duration auction.endTime = uint32(block.timestamp) + auction.duration; auction.shareUser = shareUser; _distributeBidFunds(0, auctionId, msg.value, msg.sender); } else { // Cache and update bidder state before a possible reentrancy (via the value transfer) uint256 originalAmount = auction.amount; address originalBidder = auction.bidder; auction.amount = msg.value; auction.bidder = msg.sender; auction.shareUser = shareUser; // When a bid outbids another, check to see if a time extension should apply. if (auction.endTime - uint32(block.timestamp) < auction.extensionDuration) { auction.endTime = uint32(block.timestamp) + auction.extensionDuration; } _distributeBidFunds(originalAmount, auctionId, msg.value, msg.sender); // Refund the previous bidder _sendValueWithFallbackWithdrawWithLowGasLimit(originalBidder, originalAmount); } emit ReserveAuctionBidPlaced(auctionId, msg.sender, msg.value, auction.endTime); } /** * @notice Once the countdown has expired for an auction, anyone can settle the auction. * This will send the NFT to the highest bidder and distribute funds. */ function finalizeReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.endTime > 0, "NFTMarketReserveAuction: Auction was already settled"); require(auction.endTime < uint32(block.timestamp), "NFTMarketReserveAuction: Auction still in progress"); delete nftTokenIdToAuctionId[auction.tokenId]; delete auctionIdToAuction[auctionId]; caAsset.transferFrom(address(this), auction.bidder, auction.tokenId); _distributeFunds(auction.tokenId, auction.seller, auction.shareUser, auction.amount); emit ReserveAuctionFinalized(auctionId, auction.seller, auction.bidder, auction.tokenId, auction.amount); } /** * @notice Returns the minimum amount a bidder must spend to participate in an auction. */ function getMinBidAmount(uint256 auctionId) public view returns (uint256) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; if (auction.endTime == 0) { return auction.amount; } return _getMinBidAmountForReserveAuction(auction.amount); } /** * @dev Determines the minimum bid amount when outbidding another user. */ function _getMinBidAmountForReserveAuction(uint256 currentBidAmount) private view returns (uint256) { uint256 minIncrement = currentBidAmount * _minPercentIncrementInBasisPoints / BASIS_POINTS; if (minIncrement == 0) { // The next bid must be at least 1 wei greater than the current. return currentBidAmount + 1; } return minIncrement + currentBidAmount; } /** * @notice Allows Foundation to cancel an auction, refunding the bidder and returning the NFT to the seller. * This should only be used for extreme cases such as DMCA takedown requests. The reason should always be provided. */ function adminCancelReserveAuction(uint256 auctionId, string memory reason) public onlyCAAdmin(msg.sender) { require(bytes(reason).length > 0, "NFTMarketReserveAuction: Include a reason for this cancellation"); ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.amount > 0, "NFTMarketReserveAuction: Auction not found"); delete nftTokenIdToAuctionId[auction.tokenId]; delete auctionIdToAuction[auctionId]; caAsset.transferFrom(address(this), auction.seller, auction.tokenId); if (auction.bidder != address(0)) { _sendValueWithFallbackWithdrawWithMediumGasLimit(auction.bidder, auction.amount); } emit ReserveAuctionCanceledByAdmin(auctionId, reason); } } /** * @title A market for NFTs on CA. * @dev This top level file holds no data directly to ease future upgrades. */ contract CANFTMarket is ReentrancyGuard, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction, NFTMarketReserveAuction { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ constructor (IAccessControl access, ICAAsset caAsset, address payable treasury) NFTMarketFees(caAsset, treasury) NFTMarketReserveAuction(access) { } /** * @notice Allows Foundation to update the market configuration. */ function adminUpdateConfig( uint32 minPercentIncrementInBasisPoints, uint32 duration, uint32 _caPoints, uint32 _artistPoints, uint32 _sellerPoints, uint32 _auctionAwardPoints, uint32 _sharePoints ) public onlyCAAdmin(msg.sender) { _updateReserveAuctionConfig(minPercentIncrementInBasisPoints, duration); _updateMarketFees(_caPoints, _artistPoints, _sellerPoints, _auctionAwardPoints, _sharePoints); } /** * @dev Allows for the ability to extract stuck ether * @dev Only callable from owner */ function withdrawStuckEther(address _withdrawalAccount) onlyCAAdmin(msg.sender) public { require(_withdrawalAccount != address(0), "Invalid address provided"); payable(_withdrawalAccount).transfer(address(this).balance); } }
Anytime fees are distributed that indicates the first sale is complete, which will not change state during a secondary sale. This must come after the `getFees` call above as this state is considered in the function.
nftContractToTokenIdToFirstSaleCompleted[tokenId] = true;
6,577,129
[ 1, 2961, 957, 1656, 281, 854, 16859, 716, 8527, 326, 1122, 272, 5349, 353, 3912, 16, 1492, 903, 486, 2549, 919, 4982, 279, 9946, 272, 5349, 18, 1220, 1297, 12404, 1839, 326, 1375, 588, 2954, 281, 68, 745, 5721, 487, 333, 919, 353, 7399, 316, 326, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 290, 1222, 8924, 774, 1345, 28803, 3759, 30746, 9556, 63, 2316, 548, 65, 273, 638, 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 ]
./full_match/1/0xE1b06a2A0DBcC98BD4C75027Ddd434531CcD603f/sources/contracts/token/Soar.sol
treasury (1x) swap eth to treasury zap amount swap add liquidity
function _swapTax() internal swapping { address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); uint256 balance = pendingTax; delete pendingTax; uint256 treasuryAmount = balance / 5; if (treasuryAmount > 0) { uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( treasuryAmount, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance - balanceBefore; } if (liquidityAmount > 0) { IUniswapV2Pair pair = IUniswapV2Pair( IUniswapV2Factory(router.factory()).getPair( address(this), router.WETH() ) ); (uint256 rsv0, uint256 rsv1, ) = pair.getReserves(); uint256 sellAmount = _calculateSwapInAmount( pair.token0() == address(this) ? rsv0 : rsv1, liquidityAmount ); router.swapExactTokensForETHSupportingFeeOnTransferTokens( sellAmount, 0, path, address(this), block.timestamp ); address(this), liquidityAmount - sellAmount, 0, 0, lpProvider, block.timestamp ); } }
4,971,146
[ 1, 27427, 345, 22498, 261, 21, 92, 13, 7720, 13750, 358, 9787, 345, 22498, 11419, 3844, 7720, 527, 4501, 372, 24237, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 22270, 7731, 1435, 2713, 7720, 1382, 288, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 1758, 12, 2211, 1769, 203, 3639, 589, 63, 21, 65, 273, 4633, 18, 59, 1584, 44, 5621, 203, 203, 3639, 2254, 5034, 11013, 273, 4634, 7731, 31, 203, 3639, 1430, 4634, 7731, 31, 203, 203, 3639, 2254, 5034, 9787, 345, 22498, 6275, 273, 11013, 342, 1381, 31, 203, 3639, 309, 261, 27427, 345, 22498, 6275, 405, 374, 13, 288, 203, 5411, 2254, 5034, 11013, 4649, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 5411, 4633, 18, 22270, 14332, 5157, 1290, 1584, 44, 6289, 310, 14667, 1398, 5912, 5157, 12, 203, 7734, 9787, 345, 22498, 6275, 16, 203, 7734, 374, 16, 203, 7734, 589, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 1203, 18, 5508, 203, 5411, 11272, 203, 203, 5411, 2254, 5034, 3844, 1584, 44, 273, 1758, 12, 2211, 2934, 12296, 300, 11013, 4649, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 549, 372, 24237, 6275, 405, 374, 13, 288, 203, 5411, 467, 984, 291, 91, 438, 58, 22, 4154, 3082, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 203, 7734, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 10717, 18, 6848, 1435, 2934, 588, 4154, 12, 203, 10792, 1758, 12, 2211, 3631, 203, 10792, 4633, 18, 59, 1584, 44, 1435, 203, 7734, 262, 203, 5411, 11272, 203, 203, 5411, 261, 11890, 5034, 3597, 90, 20, 16, 2254, 2 ]
./partial_match/1/0x860744711d50e6671BF1c8e40eCEDaB7D53Ca3EA/sources/XChanger.sol
oneSplit parts, 1-100 affects gas usage
uint public oneSplitParts;
2,865,065
[ 1, 476, 5521, 2140, 16, 404, 17, 6625, 30058, 16189, 4084, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 1071, 1245, 5521, 4305, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8281f2bECfF37326Eb6cBE33527434611558B031/sources/PoolController.sol
solhint-disable-line
pool.updatedAt = block.timestamp;
4,153,857
[ 1, 18281, 11317, 17, 8394, 17, 1369, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2845, 18, 7007, 861, 273, 1203, 18, 5508, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0000000000f5A96Dc85959cAeb0Cfe680f108FB5/sources/contracts/modules/SoundMetadata.sol
* @inheritdoc ISoundMetadata/
function tokenURI(uint256 tokenId) external view returns (string memory) { uint8 tier = ISoundEditionV2(msg.sender).tokenTier(tokenId); string memory uri = baseURI(msg.sender, tier); : tokenId; string memory indexString = tokenId == goldenEggTokenId(msg.sender, tier) ? "goldenEgg" string memory tierPostfix = hasTierBaseURI ? "" : string.concat("_", LibString.toString(tier)); return string.concat(uri, indexString, tierPostfix); }
5,013,366
[ 1, 36, 10093, 4437, 772, 2277, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2254, 28, 17742, 273, 4437, 772, 41, 1460, 58, 22, 12, 3576, 18, 15330, 2934, 2316, 15671, 12, 2316, 548, 1769, 203, 3639, 533, 3778, 2003, 273, 1026, 3098, 12, 3576, 18, 15330, 16, 17742, 1769, 203, 203, 203, 203, 203, 5411, 294, 1147, 548, 31, 203, 203, 3639, 533, 3778, 770, 780, 273, 1147, 548, 422, 20465, 275, 41, 14253, 1345, 548, 12, 3576, 18, 15330, 16, 17742, 13, 203, 5411, 692, 315, 75, 1673, 275, 41, 14253, 6, 203, 203, 3639, 533, 3778, 17742, 24505, 273, 711, 15671, 2171, 3098, 692, 1408, 294, 533, 18, 16426, 2932, 67, 3113, 10560, 780, 18, 10492, 12, 88, 2453, 10019, 203, 203, 3639, 327, 533, 18, 16426, 12, 1650, 16, 770, 780, 16, 17742, 24505, 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 ]
pragma solidity ^0.5.2; import "../interfaces/IToken.sol"; /** * Library for token pair exchange. * * Has no knownledge about what the token does. Any logic deal with stable or * volatile nature of the token must put in the contract level. */ library dex { bytes32 constant ZERO_ID = bytes32(0x0); bytes32 constant LAST_ID = bytes32(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); address constant ZERO_ADDRESS = address(0x0); uint constant INPUTS_MAX = 2 ** 128; // order id works much like HDKey addresses, allows client to recover and identify // historical orders using a deterministic chain of reusable indexes. function _calcID( address maker, bytes32 index ) internal pure returns (bytes32) { return sha256(abi.encodePacked(maker, index)); } struct Order { address maker; uint haveAmount; uint wantAmount; // linked list bytes32 prev; bytes32 next; } using dex for Order; function exists(Order storage order) internal view returns(bool) { // including meta orders [0] and [FF..FF] return order.maker != ZERO_ADDRESS; } function isEmpty(Order memory order) internal pure returns(bool) { return order.haveAmount == 0 || order.wantAmount == 0; } function betterThan(Order storage o, Order storage p) internal view returns (bool) { return o.haveAmount * p.wantAmount > p.haveAmount * o.wantAmount; } // memory version of betterThan function m_betterThan(Order memory o, Order storage p) internal view returns (bool) { return o.haveAmount * p.wantAmount > p.haveAmount * o.wantAmount; } function fillableBy(Order memory o, Order storage p) internal view returns (bool) { return o.haveAmount * p.haveAmount >= p.wantAmount * o.wantAmount; } struct Book { IToken haveToken; IToken wantToken; mapping (bytes32 => Order) orders; // bytes32 top; // the highest priority (lowest sell or highest buy) // bytes32 bottom; // the lowest priority (highest sell or lowest buy) } using dex for Book; function init( Book storage book, IToken haveToken, IToken wantToken ) internal { book.haveToken = haveToken; book.wantToken = wantToken; book.orders[ZERO_ID] = Order(address(this), 0, 0, ZERO_ID, LAST_ID); // [0] meta order book.orders[LAST_ID] = Order(address(this), 0, 1, ZERO_ID, LAST_ID); // worst order meta } // read functions function topID( Book storage book ) internal view returns (bytes32) { return book.orders[ZERO_ID].next; } function bottomID( Book storage book ) internal view returns (bytes32) { return book.orders[LAST_ID].prev; } function createOrder( address maker, bytes32 index, uint haveAmount, uint wantAmount ) internal pure returns (bytes32 id, Order memory order) { // TODO move require check to API require(haveAmount > 0 && wantAmount > 0, "zero input"); require(haveAmount < INPUTS_MAX && wantAmount < INPUTS_MAX, "input over limit"); id = _calcID(maker, index); // Order storage order = book.orders[id]; // require(!order.exists(), "order index exists"); // create new order order = Order(maker, haveAmount, wantAmount, 0, 0); return (id, order); } // insert [id] as [prev].next function insertAfter( Book storage book, bytes32 id, bytes32 prev ) internal { // prev => [id] => next bytes32 next = book.orders[prev].next; book.orders[id].prev = prev; book.orders[id].next = next; book.orders[next].prev = id; book.orders[prev].next = id; } // find the next id (position) to insertAfter function find( Book storage book, Order storage newOrder, bytes32 id // [id] => newOrder ) internal view returns (bytes32) { // [junk] => [0] => order => [FF] Order storage order = book.orders[id]; do { order = book.orders[id = order.next]; } while(!newOrder.betterThan(order)); // [0] <= order <= [FF] do { order = book.orders[id = order.prev]; } while(newOrder.betterThan(order)); return id; } // memory version of find function m_find( Book storage book, Order memory newOrder, bytes32 id // [id] => newOrder ) internal view returns (bytes32) { // [junk] => [0] => order => [FF] Order storage order = book.orders[id]; do { order = book.orders[id = order.next]; } while(!newOrder.m_betterThan(order)); // [0] <= order <= [FF] do { order = book.orders[id = order.prev]; } while(newOrder.m_betterThan(order)); return id; } // place the new order into its correct position function place( Book storage book, bytes32 id, Order memory order, bytes32 assistingID ) internal { require(!book.orders[id].exists(), "order index exists"); book.orders[id] = order; bytes32 prev = book.m_find(order, assistingID); book.insertAfter(id, prev); } // NOTE: this function does not payout nor refund // Use payout/refund/fill instead function _remove( Book storage book, bytes32 id ) internal { // TODO: handle order outside of the book, where next or prev is nil Order storage order = book.orders[id]; // before: prev => order => next // after: prev ==========> next book.orders[order.prev].next = order.next; book.orders[order.next].prev = order.prev; delete book.orders[id]; } function payout( Book storage book, Order memory order ) internal { if (order.wantAmount > 0) { book.wantToken.transfer(order.maker, order.wantAmount); } order.wantAmount = 0; order.haveAmount = 0; } function payout( Book storage book, bytes32 id ) internal { Order memory order = book.orders[id]; if (order.wantAmount > 0) { book.wantToken.transfer(order.maker, order.wantAmount); } book._remove(id); } function refund( Book storage book, Order memory order ) internal { if (order.haveAmount > 0) { book.haveToken.transfer(order.maker, order.haveAmount); } order.haveAmount = 0; order.wantAmount = 0; } function refund( Book storage book, bytes32 id ) internal { Order memory order = book.orders[id]; if (order.haveAmount > 0) { book.haveToken.transfer(order.maker, order.haveAmount); } book._remove(id); } function payoutPartial( Book storage book, Order memory order, uint fillableHave, uint fillableWant ) internal { require (fillableHave <= order.haveAmount, "PP: fillable > have"); require (fillableWant <= order.wantAmount, "PP: fillable > want"); order.haveAmount -= fillableHave; // safe order.wantAmount -= fillableWant; // safe book.wantToken.transfer(order.maker, fillableWant); } function payoutPartial( Book storage book, bytes32 id, uint fillableHave, uint fillableWant ) internal { Order storage order = book.orders[id]; require (fillableHave <= order.haveAmount, "PP: fillable > have"); require (fillableWant <= order.wantAmount, "PP: fillable > want"); order.haveAmount -= fillableHave; // safe order.wantAmount -= fillableWant; // safe book.wantToken.transfer(order.maker, fillableWant); if (order.isEmpty()) { book.refund(id); } } function fill( Book storage orderBook, Order memory order, Book storage redroBook ) internal { bytes32 redroID = redroBook.topID(); while (redroID != LAST_ID) { if (order.isEmpty()) { break; } Order storage redro = redroBook.orders[redroID]; if (!order.fillableBy(redro)) { break; } if (order.wantAmount < redro.haveAmount) { uint fillable = order.wantAmount * redro.wantAmount / redro.haveAmount; // partially payout the redro redroBook.payoutPartial(redroID, order.wantAmount, fillable); // fully spent the order and stop orderBook.payoutPartial(order, fillable, order.wantAmount); break; } // partially payout order orderBook.payoutPartial(order, redro.wantAmount, redro.haveAmount); // fully payout redro redroBook.payout(redroID); // next order redroID = redroBook.topID(); } } function absorb( Book storage book, bool useHaveAmount, uint target ) internal returns(uint totalBMT, uint totalAMT) { bytes32 id = book.topID(); while(id != LAST_ID && totalAMT < target) { Order storage order = book.orders[id]; uint amt = useHaveAmount ? order.haveAmount : order.wantAmount; uint bmt = useHaveAmount ? order.wantAmount : order.haveAmount; uint fillableAMT = target - totalAMT; // safe if (amt <= fillableAMT) { // fill the order book.haveToken.dexBurn(order.haveAmount); book.wantToken.dexMint(order.wantAmount); // emit FullFill(id, order.maker); bytes32 next = order.next; book.payout(id); id = next; } else { // partial order fill bmt = bmt * fillableAMT / amt; amt = fillableAMT; if (totalBMT + bmt < totalBMT) { // overflow: stop the absorption prematurely return (totalBMT, totalAMT); } uint fillableHave = useHaveAmount ? amt : bmt; uint fillableWant = useHaveAmount ? bmt : amt; // fill the partial order book.haveToken.dexBurn(fillableHave); book.wantToken.dexMint(fillableWant); // emit PartialFill(id, order.maker); book.payoutPartial(id, fillableHave, fillableWant); // extra step to make sure the loop will stop after this id = LAST_ID; } totalBMT += bmt; // safe totalAMT += amt; // safe } // not enough order, return all we have return (totalBMT, totalAMT); } }
emit PartialFill(id, order.maker);
book.payoutPartial(id, fillableHave, fillableWant);
6,393,597
[ 1, 18356, 19060, 8026, 12, 350, 16, 1353, 18, 29261, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 6978, 18, 84, 2012, 9447, 12, 350, 16, 3636, 429, 17944, 16, 3636, 429, 59, 970, 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 ]
pragma solidity ^0.4.23; import "./ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; /** * @title CowBreeding * @dev Cow Basic Implementation to breed them and provides basic functions. */ contract CowBreeding is Ownable { using SafeMath for uint256; event Breeding(uint tokenId, string cowType, string cowSex); uint cowDigits = 10; uint cowModulus = 10 ** cowDigits; struct Cow { uint cowNum; uint cowMom; uint birthDate; string types; string sex; } Cow[] public cows; // Mapping from cow ID to owner mapping (uint => address) public cowToOwner; // Mapping from owner to number of owned cow mapping (address => uint) ownerCowCount; // Mapping from token ID to number of cows mapping (uint => uint) idToCowNum; // Mapping from number of cows to token ID mapping (uint => uint) cowNumToId; modifier onlyOwnerOf(address _ownerOf) { require(msg.sender == _ownerOf); _; } /** * @dev Internal function to give birth of a cow with variables * @param _cowNum new cow identity number * @param _cowMom new cow's mother identity number * @param _types new cow's type such as BrownSwiss * @param _sex new cow's sex male or female */ function _cowBirth(uint _cowNum, uint _cowMom, string _types, string _sex) internal { uint id = cows.push(Cow(_cowNum, _cowMom, block.timestamp, _types, _sex)) - 1; idToCowNum[id] = _cowNum; cowNumToId[_cowNum] = id; cowToOwner[_cowNum] = msg.sender; ownerCowCount[msg.sender] = ownerCowCount[msg.sender].add(1); emit Breeding(_cowNum, _types, _sex); } /** * @dev Gives birth of a cow with variables * @param _cowMom new cow's mother identity number * @param _types new cow's type such as BrownSwiss * @param _sex new cow's sex male or female */ function cowBirth(uint _cowMom, string _types, string _sex) public { // Generate a unique identifier for cows uint _cowNum = uint(keccak256(abi.encodePacked(msg.sender, blockhash(block.number - 1)))) % cowModulus; _cowBirth(_cowNum, _cowMom, _types, _sex); } /** * @dev Gets cows in struct from the owner address * @param _owner cow owner address * @return uint array of cow structs */ function getCowsByOwner(address _owner) external view returns (uint[]) { uint[] memory cowsByOwner = new uint[](ownerCowCount[_owner]); uint counter = 0; uint number; for (uint i = 0; i < cows.length; i++) { number = idToCowNum[i]; if (cowToOwner[number] == _owner) { cowsByOwner[counter] = number; counter = counter.add(1); } } return cowsByOwner; } /** * @dev Gets cow counts from the owner address * @param _owner cow owner address * @return uint of cow counts of the owner */ function getCountByOwner(address _owner) external view returns (uint) { return ownerCowCount[_owner]; } /** * @dev Gets number of cows from the cow id * @param _cowNum cow identity number * @return uint of cow id */ function getIdByCowNum(uint _cowNum) external view returns (uint) { return cowNumToId[_cowNum]; } /** * @dev Gets an owner address from a cow identity number * @param _cowNum cow identity number * @return address of the owner of the mentioned identity number */ function getOwnerByCow(uint _cowNum) public view returns (address) { return cowToOwner[_cowNum]; } }
* @dev Gives birth of a cow with variables @param _cowMom new cow's mother identity number @param _types new cow's type such as BrownSwiss @param _sex new cow's sex male or female/ Generate a unique identifier for cows
function cowBirth(uint _cowMom, string _types, string _sex) public { uint _cowNum = uint(keccak256(abi.encodePacked(msg.sender, blockhash(block.number - 1)))) % cowModulus; _cowBirth(_cowNum, _cowMom, _types, _sex); }
1,028,918
[ 1, 43, 3606, 17057, 434, 279, 276, 543, 598, 3152, 225, 389, 71, 543, 49, 362, 394, 276, 543, 1807, 312, 3011, 4215, 1300, 225, 389, 2352, 394, 276, 543, 1807, 618, 4123, 487, 605, 26253, 6050, 1054, 225, 389, 20909, 394, 276, 543, 1807, 19631, 312, 5349, 578, 284, 351, 5349, 19, 6654, 279, 3089, 2756, 364, 276, 543, 87, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 276, 543, 25791, 12, 11890, 389, 71, 543, 49, 362, 16, 533, 389, 2352, 16, 533, 389, 20909, 13, 1071, 288, 203, 565, 2254, 389, 71, 543, 2578, 273, 2254, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 16, 1203, 2816, 12, 2629, 18, 2696, 300, 404, 3719, 3719, 738, 276, 543, 1739, 17284, 31, 203, 565, 389, 71, 543, 25791, 24899, 71, 543, 2578, 16, 389, 71, 543, 49, 362, 16, 389, 2352, 16, 389, 20909, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-04-02 */ // File: contracts/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/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: contracts/ERC20.sol pragma solidity >=0.6.0 <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 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 { } } // File: contracts/ERC20Burnable.sol pragma solidity >=0.6.0 <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 ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // File: contracts/Pausable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/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: contracts/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: contracts/AccessControl.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // File: contracts/Tribe.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Forked from Uniswap's UNI // Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code contract Tribe { /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "Feii Tribe"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "TRIBAL"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation // solhint-disable-next-line const-name-snakecase uint public totalSupply = 1_000_000_000e18; // 1 billion Tribe /// @notice Address which may mint new tokens address public minter; /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when the minter address is changed event MinterChanged(address minter, address newMinter); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Tribe token * @param account The initial account to grant all the tokens * @param minter_ The account with minting ability */ constructor(address account, address minter_) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); minter = minter_; emit MinterChanged(address(0), minter); } /** * @notice Change the minter address * @param minter_ The address of the new minter */ function setMinter(address minter_) external { require(msg.sender == minter, "Tribe: only the minter can change the minter address"); emit MinterChanged(minter, minter_); minter = minter_; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function mint(address dst, uint rawAmount) external { require(msg.sender == minter, "Tribe: only the minter can mint"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); // mint the amount uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits"); totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(signatory == owner, "Tribe: unauthorized"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "Tribe: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Tribe: invalid signature"); require(nonce == nonces[signatory]++, "Tribe: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= expiry, "Tribe: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Tribe: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Tribe: cannot transfer from the zero address"); require(dst != address(0), "Tribe: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Tribe: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File: contracts/IFei.sol pragma solidity ^0.6.2; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } // File: contracts/IPermissions.sol pragma solidity ^0.6.0; /// @title Permissions interface /// @author Fei Protocol interface IPermissions { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // File: contracts/ICore.sol pragma solidity ^0.6.0; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function setGenesisGroup(address _genesisGroup) external; function allocateTribe(address to, uint256 amount) external; // ----------- Genesis Group only state changing api ----------- function completeGenesisGroup() external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); function genesisGroup() external view returns (address); function hasGenesisGroupCompleted() external view returns (bool); } // File: contracts/ICoreRef.sol pragma solidity ^0.6.0; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address core) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); } // File: contracts/CoreRef.sol pragma solidity ^0.6.0; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice CoreRef constructor /// @param core Fei Core to reference constructor(address core) public { _core = ICore(core); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } modifier onlyGenesisGroup() { require( msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup" ); _; } modifier postGenesis() { require( _core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period" ); _; } modifier nonContract() { require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract"); _; } /// @notice set new Core reference address /// @param core the new core address function setCore(address core) external override onlyGovernor { _core = ICore(core); emit CoreUpdate(core); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(uint256 amount) internal { fei().mint(address(this), amount); } } // File: contracts/IIncentive.sol pragma solidity ^0.6.2; /// @title incentive contract interface /// @author Fei Protocol /// @notice Called by FEI token contract when transferring with an incentivized address /// @dev should be appointed as a Minter or Burner as needed interface IIncentive { // ----------- Fei only state changing api ----------- /// @notice apply incentives on transfer /// @param sender the sender address of the FEI /// @param receiver the receiver address of the FEI /// @param operator the operator (msg.sender) of the transfer /// @param amount the amount of FEI transferred function incentivize( address sender, address receiver, address operator, uint256 amount ) external; } // File: contracts/Fei.sol pragma solidity ^0.6.0; /// @title FEI stablecoin /// @author Fei Protocol contract Fei is IFei, ERC20Burnable, CoreRef { /// @notice get associated incentive contract, 0 address if N/A mapping(address => address) public override incentiveContract; // solhint-disable-next-line var-name-mixedcase bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; /// @notice Fei token constructor /// @param core Fei Core address to reference constructor(address core) public ERC20("Feii USD", "FEII") CoreRef(core) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name())), keccak256(bytes("1")), chainId, address(this) ) ); } /// @param account the account to incentivize /// @param incentive the associated incentive contract function setIncentiveContract(address account, address incentive) external override onlyGovernor { incentiveContract[account] = incentive; emit IncentiveContractUpdate(account, incentive); } /// @notice mint FEI tokens /// @param account the account to mint to /// @param amount the amount to mint function mint(address account, uint256 amount) external override onlyMinter whenNotPaused { _mint(account, amount); emit Minting(account, msg.sender, amount); } /// @notice burn FEI tokens from caller /// @param amount the amount to burn function burn(uint256 amount) public override(IFei, ERC20Burnable) { super.burn(amount); emit Burning(msg.sender, msg.sender, amount); } /// @notice burn FEI tokens from specified account /// @param account the account to burn from /// @param amount the amount to burn function burnFrom(address account, uint256 amount) public override(IFei, ERC20Burnable) onlyBurner whenNotPaused { _burn(account, amount); emit Burning(account, msg.sender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal override { super._transfer(sender, recipient, amount); _checkAndApplyIncentives(sender, recipient, amount); } function _checkAndApplyIncentives( address sender, address recipient, uint256 amount ) internal { // incentive on sender address senderIncentive = incentiveContract[sender]; if (senderIncentive != address(0)) { IIncentive(senderIncentive).incentivize( sender, recipient, msg.sender, amount ); } // incentive on recipient address recipientIncentive = incentiveContract[recipient]; if (recipientIncentive != address(0)) { IIncentive(recipientIncentive).incentivize( sender, recipient, msg.sender, amount ); } // incentive on operator address operatorIncentive = incentiveContract[msg.sender]; if ( msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0) ) { IIncentive(operatorIncentive).incentivize( sender, recipient, msg.sender, amount ); } // all incentive, if active applies to every transfer address allIncentive = incentiveContract[address(0)]; if (allIncentive != address(0)) { IIncentive(allIncentive).incentivize( sender, recipient, msg.sender, amount ); } } /// @notice permit spending of FEI /// @param owner the FEI holder /// @param spender the approved operator /// @param value the amount approved /// @param deadline the deadline after which the approval is no longer valid function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { // solhint-disable-next-line not-rely-on-time require(deadline >= block.timestamp, "Fei: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "Fei: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // File: contracts/Permissions.sol pragma solidity ^0.6.0; /// @title Access control module for Core /// @author Fei Protocol contract Permissions is IPermissions, AccessControl { bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE"); bytes32 public constant GOVERN_ROLE = keccak256("GOVERN_ROLE"); bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); constructor() public { // Appointed as a governor so guardian can have indirect access to revoke ability _setupGovernor(address(this)); _setRoleAdmin(MINTER_ROLE, GOVERN_ROLE); _setRoleAdmin(BURNER_ROLE, GOVERN_ROLE); _setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE); _setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE); _setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE); } modifier onlyGovernor() { require( isGovernor(msg.sender), "Permissions: Caller is not a governor" ); _; } modifier onlyGuardian() { require(isGuardian(msg.sender), "Permissions: Caller is not a guardian"); _; } /// @notice creates a new role to be maintained /// @param role the new role id /// @param adminRole the admin role id for `role` /// @dev can also be used to update admin of existing role function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor { _setRoleAdmin(role, adminRole); } /// @notice grants minter role to address /// @param minter new minter function grantMinter(address minter) external override onlyGovernor { grantRole(MINTER_ROLE, minter); } /// @notice grants burner role to address /// @param burner new burner function grantBurner(address burner) external override onlyGovernor { grantRole(BURNER_ROLE, burner); } /// @notice grants controller role to address /// @param pcvController new controller function grantPCVController(address pcvController) external override onlyGovernor { grantRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice grants governor role to address /// @param governor new governor function grantGovernor(address governor) external override onlyGovernor { grantRole(GOVERN_ROLE, governor); } /// @notice grants guardian role to address /// @param guardian new guardian function grantGuardian(address guardian) external override onlyGovernor { grantRole(GUARDIAN_ROLE, guardian); } /// @notice revokes minter role from address /// @param minter ex minter function revokeMinter(address minter) external override onlyGovernor { revokeRole(MINTER_ROLE, minter); } /// @notice revokes burner role from address /// @param burner ex burner function revokeBurner(address burner) external override onlyGovernor { revokeRole(BURNER_ROLE, burner); } /// @notice revokes pcvController role from address /// @param pcvController ex pcvController function revokePCVController(address pcvController) external override onlyGovernor { revokeRole(PCV_CONTROLLER_ROLE, pcvController); } /// @notice revokes governor role from address /// @param governor ex governor function revokeGovernor(address governor) external override onlyGovernor { revokeRole(GOVERN_ROLE, governor); } /// @notice revokes guardian role from address /// @param guardian ex guardian function revokeGuardian(address guardian) external override onlyGovernor { revokeRole(GUARDIAN_ROLE, guardian); } /// @notice revokes a role from address /// @param role the role to revoke /// @param account the address to revoke the role from function revokeOverride(bytes32 role, address account) external override onlyGuardian { require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor"); // External call because this contract is appointed as a governor and has access to revoke this.revokeRole(role, account); } /// @notice checks if address is a minter /// @param _address address to check /// @return true _address is a minter function isMinter(address _address) external view override returns (bool) { return hasRole(MINTER_ROLE, _address); } /// @notice checks if address is a burner /// @param _address address to check /// @return true _address is a burner function isBurner(address _address) external view override returns (bool) { return hasRole(BURNER_ROLE, _address); } /// @notice checks if address is a controller /// @param _address address to check /// @return true _address is a controller function isPCVController(address _address) external view override returns (bool) { return hasRole(PCV_CONTROLLER_ROLE, _address); } /// @notice checks if address is a governor /// @param _address address to check /// @return true _address is a governor // only virtual for testing mock override function isGovernor(address _address) public view virtual override returns (bool) { return hasRole(GOVERN_ROLE, _address); } /// @notice checks if address is a guardian /// @param _address address to check /// @return true _address is a guardian function isGuardian(address _address) public view override returns (bool) { return hasRole(GUARDIAN_ROLE, _address); } function _setupGovernor(address governor) internal { _setupRole(GOVERN_ROLE, governor); } } // File: contracts/Core.sol pragma solidity ^0.6.0; /// @title Source of truth for Fei Protocol /// @author Fei Protocol /// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury contract Core is ICore, Permissions, Initializable { /// @notice the address of the FEI contract IFei public override fei; /// @notice the address of the TRIBE contract IERC20 public override tribe; /// @notice the address of the GenesisGroup contract address public override genesisGroup; /// @notice determines whether in genesis period or not bool public override hasGenesisGroupCompleted; function init() external override initializer { _setupGovernor(msg.sender); Fei _fei = new Fei(address(this)); _setFei(address(_fei)); Tribe _tribe = new Tribe(address(this), msg.sender); _setTribe(address(_tribe)); } /// @notice sets Fei address to a new address /// @param token new fei address function setFei(address token) external override onlyGovernor { _setFei(token); } /// @notice sets Tribe address to a new address /// @param token new tribe address function setTribe(address token) external override onlyGovernor { _setTribe(token); } /// @notice sets Genesis Group address /// @param _genesisGroup new genesis group address function setGenesisGroup(address _genesisGroup) external override onlyGovernor { genesisGroup = _genesisGroup; emit GenesisGroupUpdate(_genesisGroup); } /// @notice sends TRIBE tokens from treasury to an address /// @param to the address to send TRIBE to /// @param amount the amount of TRIBE to send function allocateTribe(address to, uint256 amount) external override onlyGovernor { IERC20 _tribe = tribe; require( _tribe.balanceOf(address(this)) >= amount, "Core: Not enough Tribe" ); _tribe.transfer(to, amount); emit TribeAllocation(to, amount); } /// @notice marks the end of the genesis period /// @dev can only be called once function completeGenesisGroup() external override { require( !hasGenesisGroupCompleted, "Core: Genesis Group already complete" ); require( msg.sender == genesisGroup, "Core: Caller is not Genesis Group" ); hasGenesisGroupCompleted = true; // solhint-disable-next-line not-rely-on-time emit GenesisPeriodComplete(block.timestamp); } function _setFei(address token) internal { fei = IFei(token); emit FeiUpdate(token); } function _setTribe(address token) internal { tribe = IERC20(token); emit TribeUpdate(token); } }
@notice marks the end of the genesis period @dev can only be called once solhint-disable-next-line not-rely-on-time
function completeGenesisGroup() external override { require( !hasGenesisGroupCompleted, "Core: Genesis Group already complete" ); require( msg.sender == genesisGroup, "Core: Caller is not Genesis Group" ); hasGenesisGroupCompleted = true; emit GenesisPeriodComplete(block.timestamp); }
10,794,199
[ 1, 17439, 326, 679, 434, 326, 21906, 3879, 225, 848, 1338, 506, 2566, 3647, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3912, 7642, 16786, 1114, 1435, 3903, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 401, 5332, 7642, 16786, 1114, 9556, 16, 203, 5411, 315, 4670, 30, 31637, 3756, 1818, 3912, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 21906, 1114, 16, 203, 5411, 315, 4670, 30, 20646, 353, 486, 31637, 3756, 6, 203, 3639, 11272, 203, 203, 3639, 711, 7642, 16786, 1114, 9556, 273, 638, 31, 203, 203, 3639, 3626, 31637, 5027, 6322, 12, 2629, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0x3417A7c981d81C3230Ef34d9884eD7F360140342/sources/HmstrChefTest.sol
Withdraw LP tokens from HmstrChef.
function withdraw(uint256 _pid, uint256 _amount) public { 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.accHmstrPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeHmstrTransfer(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.accHmstrPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
11,231,805
[ 1, 1190, 9446, 511, 52, 2430, 628, 670, 81, 701, 39, 580, 74, 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 ]
[ 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, 598, 9446, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 1918, 9446, 30, 486, 7494, 8863, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 44, 81, 701, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 3639, 309, 12, 9561, 405, 374, 13, 288, 203, 5411, 4183, 44, 81, 701, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 3639, 309, 24899, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 3639, 289, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 44, 81, 701, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 1769, 203, 3639, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 6610, 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 ]
// SPDX-License-Identifier: GNU /// @notice adapted from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol pragma solidity 0.7.6; import "../OracleCommon.sol"; import "../../_openzeppelin/math/SafeMath.sol"; import '../../_uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import '../../_uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '../../_uniswap/lib/contracts/libraries/FixedPoint.sol'; import '../../_uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol'; import '../../_uniswap/v2-periphery/contracts/libraries/UniswapV2Library.sol'; /** @notice A oracle that uses 2 TWAP periods and uses the lower of the 2 values. Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period, Periodicity is fixed at deployment time. Index (usually USD) token is fixed at deployment time. A single deployment can be shared by multiple oneToken clients and can observe multiple base tokens. Non-USD index tokens are possible. Such deployments can used as interim oracles in Composite Oracles. They should NOT be registered because they are not, by definition, valid sources of USD quotes. Example calculation MPH/ETH -> ETH/USD 1hr and MPH/ETH -> ETH/USD 24hr take the lower value and return. This is a safety net to help prevent price manipulation. This oracle combines 2 TWAPs to save on gas for keeping seperate oracles for these 2 PERIODS. */ contract UniswapOracleTWAPCompare is OracleCommon { using FixedPoint for *; using SafeMath for uint256; uint256 public immutable PERIOD_1; uint256 public immutable PERIOD_2; address public immutable uniswapFactory; struct Pair { address token0; address token1; uint256 price0CumulativeLast; uint256 price1CumulativeLast; uint32 blockTimestampLast; FixedPoint.uq112x112 price0Average; FixedPoint.uq112x112 price1Average; } mapping(address => Pair) period_1_pairs; mapping(address => Pair) period_2_pairs; /** @notice the indexToken (index token), averaging period and uniswapfactory cannot be changed post-deployment @dev deploy multiple instances to support different configurations @param oneTokenFactory_ oneToken factory to bind to @param uniswapFactory_ external factory contract needed by the uniswap library @param indexToken_ the index token to use for valuations. If not a usd collateral token then the Oracle should not be registered in the factory but it can be used by CompositeOracles. @param period_1_ the averaging period to use for price smoothing @param period_2_ the averaging period to use for price smoothing */ constructor(address oneTokenFactory_, address uniswapFactory_, address indexToken_, uint256 period_1_, uint256 period_2_) OracleCommon(oneTokenFactory_, "ICHI TWAP Compare Uniswap Oracle", indexToken_) { require(uniswapFactory_ != NULL_ADDRESS, "UniswapOracleTWAPCompare: uniswapFactory cannot be empty"); require(period_1_ > 0, "UniswapOracleTWAPCompare: period must be > 0"); require(period_2_ > 0, "UniswapOracleTWAPCompare: period must be > 0"); uniswapFactory = uniswapFactory_; PERIOD_1 = period_1_; PERIOD_2 = period_2_; indexToken = indexToken_; } /** @notice configures parameters for a pair, token versus indexToken @dev initializes the first time, then does no work. Initialized from the Factory when assigned to an asset. @param token the base token. index is established at deployment time and cannot be changed */ function init(address token) external onlyModuleOrFactory override { require(token != NULL_ADDRESS, "UniswapOracleTWAPCompare: token cannot be null"); IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); // this condition should never be false require(address(_pair) != NULL_ADDRESS, "UniswapOracleTWAPCompare: unknown pair"); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; if(p1.token0 == NULL_ADDRESS && p2.token0 == NULL_ADDRESS) { p1.token0 = _pair.token0(); p2.token0 = _pair.token0(); p1.token1 = _pair.token1(); p2.token1 = _pair.token1(); p1.price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0) p2.price0CumulativeLast = _pair.price0CumulativeLast(); p1.price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1) p2.price1CumulativeLast = _pair.price1CumulativeLast(); uint112 reserve0; uint112 reserve1; (reserve0, reserve1, p1.blockTimestampLast) = _pair.getReserves(); p2.blockTimestampLast = p1.blockTimestampLast; require(reserve0 != 0 && reserve1 != 0, 'UniswapOracleTWAPCompare: NO_RESERVES'); // ensure that there's liquidity in the pair emit OracleInitialized(msg.sender, token, indexToken); } } /** @notice returns equivalent indexTokens for amountIn, token @dev index token is established at deployment time @param token ERC20 token @param amountTokens quantity, token precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function read(address token, uint256 amountTokens) external view override returns(uint256 amountUsd, uint256 volatility) { amountUsd = tokensToNormalized(indexToken, consult(token, amountTokens)); volatility = 1; } /** @notice returns equivalent baseTokens for amountUsd, indexToken @dev index token is established at deployment time @param token ERC20 token @param amountTokens quantity, token precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function amountRequired(address token, uint256 amountUsd) external view override returns(uint256 amountTokens, uint256 volatility) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; require(token == p1.token0 || token == p1.token1, 'UniswapOracleTWAPCompare: INVALID_TOKEN'); require(p1.price0CumulativeLast > 0 && p2.price0CumulativeLast > 0, "UniswapOracleTWAPCompare: Gathering history. Try again later"); amountUsd = normalizedToTokens(indexToken, amountUsd); uint256 p1Tokens = (token == p1.token0 ? p1.price0Average : p1.price1Average).reciprocal().mul(amountUsd).decode144(); uint256 p2Tokens = (token == p2.token0 ? p2.price0Average : p2.price1Average).reciprocal().mul(amountUsd).decode144(); if (p1Tokens > p2Tokens) { //want to take the lower price which is more larger amount of tokens amountTokens = p1Tokens; } else { amountTokens = p2Tokens; } volatility = 1; } /** @notice updates price observation history, if necessary @dev it is permissible for anyone to supply gas and update the oracle's price history. @param token baseToken to update */ function update(address token) external override { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; if(p1.token0 != NULL_ADDRESS) { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed_1 = blockTimestamp - p1.blockTimestampLast; // overflow is desired uint32 timeElapsed_2 = blockTimestamp - p2.blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update ///@ dev require() was dropped in favor of if() to make this safe to call when unsure about elapsed time if(timeElapsed_1 >= PERIOD_1) { // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed p1.price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - p1.price0CumulativeLast) / timeElapsed_1)); p1.price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - p1.price1CumulativeLast) / timeElapsed_1)); p1.price0CumulativeLast = price0Cumulative; p1.price1CumulativeLast = price1Cumulative; p1.blockTimestampLast = blockTimestamp; } if(timeElapsed_2 >= PERIOD_2) { // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed p2.price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - p2.price0CumulativeLast) / timeElapsed_2)); p2.price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - p2.price1CumulativeLast) / timeElapsed_2)); p2.price0CumulativeLast = price0Cumulative; p2.price1CumulativeLast = price1Cumulative; p2.blockTimestampLast = blockTimestamp; } // No event emitter to save gas } } // note this will always return 0 before update has been called successfully for the first time. // this will return an average over a long period of time unless someone calls the update() function. /** @notice returns equivalent indexTokens for amountIn, token @dev always returns 0 before update(token) has been called successfully for the first time. @param token baseToken to update @param amountTokens amount in token native precision @param amountOut anount in tokens, reciprocal token */ function consult(address token, uint256 amountTokens) public view returns (uint256 amountOut) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p1 = period_1_pairs[address(_pair)]; Pair storage p2 = period_2_pairs[address(_pair)]; require(token == p1.token0 || token == p1.token1, 'UniswapOracleTWAPCompare: INVALID_TOKEN'); require(p1.price0CumulativeLast > 0 && p2.price0CumulativeLast > 0, "UniswapOracleTWAPCompare: Gathering history. Try again later"); uint256 p1Out = (token == p1.token0 ? p1.price0Average : p1.price1Average).mul(amountTokens).decode144(); uint256 p2Out = (token == p2.token0 ? p2.price0Average : p2.price1Average).mul(amountTokens).decode144(); if (p1Out > p2Out) { amountOut = p2Out; } else { amountOut = p1Out; } } /** @notice discoverable internal state. Returns pair info for period 1 @param token baseToken to inspect */ function pair1Info(address token) external view returns ( address token0, address token1, uint256 price0CumulativeLast, uint256 price1CumulativeLast, uint256 price0Average, uint256 price1Average, uint32 blockTimestampLast, uint256 period ) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p = period_1_pairs[address(_pair)]; return( p.token0, p.token1, p.price0CumulativeLast, p.price1CumulativeLast, p.price0Average.mul(PRECISION).decode144(), p.price1Average.mul(PRECISION).decode144(), p.blockTimestampLast, PERIOD_1 ); } /** @notice discoverable internal state. Returns pair info for period 2 @param token baseToken to inspect */ function pair2Info(address token) external view returns ( address token0, address token1, uint256 price0CumulativeLast, uint256 price1CumulativeLast, uint256 price0Average, uint256 price1Average, uint32 blockTimestampLast, uint256 period ) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(uniswapFactory, token, indexToken)); Pair storage p = period_2_pairs[address(_pair)]; return( p.token0, p.token1, p.price0CumulativeLast, p.price1CumulativeLast, p.price0Average.mul(PRECISION).decode144(), p.price1Average.mul(PRECISION).decode144(), p.blockTimestampLast, PERIOD_2 ); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../interface/IOracle.sol"; import "../common/ICHIModuleCommon.sol"; abstract contract OracleCommon is IOracle, ICHIModuleCommon { uint256 constant NORMAL = 18; bytes32 constant public override MODULE_TYPE = keccak256(abi.encodePacked("ICHI V1 Oracle Implementation")); address public override indexToken; event OracleDeployed(address sender, string description, address indexToken); event OracleInitialized(address sender, address baseToken, address indexToken); /** @notice records the oracle description and the index that will be used for all quotes @dev oneToken implementations can share oracles @param oneTokenFactory_ oneTokenFactory to bind to @param description_ all modules have a description. No processing or validation @param indexToken_ every oracle has an index token for reporting the value of a base token */ constructor(address oneTokenFactory_, string memory description_, address indexToken_) ICHIModuleCommon(oneTokenFactory_, ModuleType.Oracle, description_) { require(indexToken_ != NULL_ADDRESS, "OracleCommon: indexToken cannot be empty"); indexToken = indexToken_; emit OracleDeployed(msg.sender, description_, indexToken_); } /** @notice oneTokens can share Oracles. Oracles must be re-initializable. They are initialized from the Factory. @param baseToken oracles _can be_ multi-tenant with separately initialized baseTokens */ function init(address baseToken) external onlyModuleOrFactory virtual override { emit OracleInitialized(msg.sender, baseToken, indexToken); } /** @notice converts normalized precision 18 amounts to token native precision amounts, truncates low-order values @param token ERC20 token contract @param amountNormal quantity in precision-18 @param amountTokens quantity scaled to token decimals() */ function normalizedToTokens(address token, uint256 amountNormal) public view override returns(uint256 amountTokens) { IERC20Extended t = IERC20Extended(token); uint256 nativeDecimals = t.decimals(); require(nativeDecimals <= 18, "OracleCommon: unsupported token precision (greater than 18)"); if(nativeDecimals == NORMAL) return amountNormal; return amountNormal / ( 10 ** (NORMAL - nativeDecimals)); } /** @notice converts token native precision amounts to normalized precision 18 amounts @param token ERC20 token contract @param amountTokens quantity scaled to token decimals @param amountNormal quantity in precision-18 */ function tokensToNormalized(address token, uint256 amountTokens) public view override returns(uint256 amountNormal) { IERC20Extended t = IERC20Extended(token); uint256 nativeDecimals = t.decimals(); require(nativeDecimals <= 18, "OracleCommon: unsupported token precision (greater than 18)"); if(nativeDecimals == NORMAL) return amountTokens; return amountTokens * ( 10 ** (NORMAL - nativeDecimals)); } } // 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: GNU pragma solidity >=0.5.0; interface IUniswapV2Factory { // event PairCreated(address indexed token0, address indexed token1, address pair, uint256); // function feeTo() external view returns (address); // function feeToSetter() external view returns (address); // // function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: GNU pragma solidity =0.7.6; interface IUniswapV2Pair { // event Approval(address indexed owner, address indexed spender, uint256 value); // event Transfer(address indexed from, address indexed to, uint256 value); // function name() external pure returns (string memory); // function symbol() external pure returns (string memory); // function decimals() external pure returns (uint8); // function totalSupply() external view returns (uint256); // function balanceOf(address owner) external view returns (uint256); // function allowance(address owner, address spender) external view returns (uint256); // // function approve(address spender, uint256 value) external returns (bool); // function transfer(address to, uint256 value) external returns (bool); // function transferFrom(address from, address to, uint256 value) external returns (bool); // function DOMAIN_SEPARATOR() external view returns (bytes32); // function PERMIT_TYPEHASH() external pure returns (bytes32); // function nonces(address owner) external view returns (uint256); // // function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; // // event Mint(address indexed sender, uint256 amount0, uint256 amount1); // event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); // event Swap( // address indexed sender, // uint256 amount0In, // uint256 amount1In, // uint256 amount0Out, // uint256 amount1Out, // address indexed to // ); event Sync(uint112 reserve0, uint112 reserve1); // function MINIMUM_LIQUIDITY() external pure returns (uint256); // function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); // function kLast() external view returns (uint256); // // function mint(address to) external returns (uint256 liquidity); // function burn(address to) external returns (uint256 amount0, uint256 amount1); // function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external; // function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './FullMath.sol'; import './Babylonian.sol'; import './BitMath.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint256 _x; } uint8 public constant RESOLUTION = 112; uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112 uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224 uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // multiply a UQ112x112 by a uint256, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) { uint256 z = 0; require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow'); return uq144x112(z); } // multiply a UQ112x112 by an int and decode, returning an int // reverts on overflow function muli(uq112x112 memory self, int256 y) internal pure returns (int256) { uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112); require(z < 2**255, 'FixedPoint::muli: overflow'); return y < 0 ? -int256(z) : int256(z); } // multiply a UQ112x112 by a UQ112x112, returning a UQ112x112 // lossy function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { if (self._x == 0 || other._x == 0) { return uq112x112(0); } uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0 uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112 uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0 uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112 // partial products uint224 upper = uint224(upper_self) * upper_other; // * 2^0 uint224 lower = uint224(lower_self) * lower_other; // * 2^-224 uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112 uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112 // so the bit shift does not overflow require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow'); // this cannot exceed 256 bits, all values are 224 bits uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION); // so the cast does not overflow require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow'); return uq112x112(uint224(sum)); } // divide a UQ112x112 by a UQ112x112, returning a UQ112x112 function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // can be lossy function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // take the reciprocal of a UQ112x112 // reverts on overflow // lossy function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero'); require(self._x != 1, 'FixedPoint::reciprocal: overflow'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // SPDX-License-Identifier: GNU pragma solidity 0.7.6; import "./UniswapV2Library.sol"; import '../../../lib/contracts/libraries/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // SPDX-License-Identifier: GNU pragma solidity 0.7.6; import '../../../v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '../../../v2-core/contracts/UniswapV2Pair.sol'; import "./UniswapSafeMath.sol"; library UniswapV2Library { using UniswapSafeMath for uint256; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } function getInitHash() public pure returns (bytes32){ bytes memory bytecode = type(UniswapV2Pair).creationCode; return keccak256(abi.encodePacked(bytecode)); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint256(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), getInitHash() )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) internal pure returns (uint256 amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut) internal pure returns (uint256 amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint256 amountIn, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint256 amountOut, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IModule.sol"; interface IOracle is IModule { function init(address baseToken) external; function update(address token) external; function indexToken() external view returns(address); /** @param token ERC20 token @param amountTokens quantity, token native precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function read(address token, uint amountTokens) external view returns(uint amountUsd, uint volatility); /** @param token ERC20 token @param amountTokens token quantity, token native precision @param amountUsd US dollar equivalent, precision 18 @param volatility metric for future use-cases */ function amountRequired(address token, uint amountUsd) external view returns(uint amountTokens, uint volatility); /** @notice converts normalized precision-18 amounts to token native precision amounts, truncates low-order values @param token ERC20 token contract @param amountNormal quantity, precision 18 @param amountTokens quantity scaled to token precision */ function normalizedToTokens(address token, uint amountNormal) external view returns(uint amountTokens); /** @notice converts token native precision amounts to normalized precision-18 amounts @param token ERC20 token contract @param amountNormal quantity, precision 18 @param amountTokens quantity scaled to token precision */ function tokensToNormalized(address token, uint amountTokens) external view returns(uint amountNormal); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../interface/IModule.sol"; import "../interface/IOneTokenFactory.sol"; import "../interface/IOneTokenV1Base.sol"; import "./ICHICommon.sol"; abstract contract ICHIModuleCommon is IModule, ICHICommon { ModuleType public immutable override moduleType; string public override moduleDescription; address public immutable override oneTokenFactory; event ModuleDeployed(address sender, ModuleType moduleType, string description); event DescriptionUpdated(address sender, string description); modifier onlyKnownToken { require(IOneTokenFactory(oneTokenFactory).isOneToken(msg.sender), "ICHIModuleCommon: msg.sender is not a known oneToken"); _; } modifier onlyTokenOwner (address oneToken) { require(msg.sender == IOneTokenV1Base(oneToken).owner(), "ICHIModuleCommon: msg.sender is not oneToken owner"); _; } modifier onlyModuleOrFactory { if(!IOneTokenFactory(oneTokenFactory).isModule(msg.sender)) { require(msg.sender == oneTokenFactory, "ICHIModuleCommon: msg.sender is not module owner, token factory or registed module"); } _; } /** @notice modules are bound to the factory at deployment time @param oneTokenFactory_ factory to bind to @param moduleType_ type number helps prevent governance errors @param description_ human-readable, descriptive only */ constructor (address oneTokenFactory_, ModuleType moduleType_, string memory description_) { require(oneTokenFactory_ != NULL_ADDRESS, "ICHIModuleCommon: oneTokenFactory cannot be empty"); require(bytes(description_).length > 0, "ICHIModuleCommon: description cannot be empty"); oneTokenFactory = oneTokenFactory_; moduleType = moduleType_; moduleDescription = description_; emit ModuleDeployed(msg.sender, moduleType_, description_); } /** @notice set a module description @param description new module desciption */ function updateDescription(string memory description) external onlyOwner override { require(bytes(description).length > 0, "ICHIModuleCommon: description cannot be empty"); moduleDescription = description; emit DescriptionUpdated(msg.sender, description); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHICommon.sol"; import "./InterfaceCommon.sol"; interface IModule is IICHICommon { function oneTokenFactory() external view returns(address); function updateDescription(string memory description) external; function moduleDescription() external view returns(string memory); function MODULE_TYPE() external view returns(bytes32); function moduleType() external view returns(ModuleType); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHIOwnable.sol"; import "./InterfaceCommon.sol"; interface IICHICommon is IICHIOwnable, InterfaceCommon {} // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; interface InterfaceCommon { enum ModuleType { Version, Controller, Strategy, MintMaster, Oracle } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; interface IICHIOwnable { function renounceOwnership() external; function transferOwnership(address newOwner) external; function owner() external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "./InterfaceCommon.sol"; interface IOneTokenFactory is InterfaceCommon { function oneTokenProxyAdmins(address) external returns(address); function deployOneTokenProxy( string memory name, string memory symbol, address governance, address version, address controller, address mintMaster, address memberToken, address collateral, address oneTokenOracle ) external returns(address newOneTokenProxy, address proxyAdmin); function admitModule(address module, ModuleType moduleType, string memory name, string memory url) external; function updateModule(address module, string memory name, string memory url) external; function removeModule(address module) external; function admitForeignToken(address foreignToken, bool collateral, address oracle) external; function updateForeignToken(address foreignToken, bool collateral) external; function removeForeignToken(address foreignToken) external; function assignOracle(address foreignToken, address oracle) external; function removeOracle(address foreignToken, address oracle) external; /** * View functions */ function MODULE_TYPE() external view returns(bytes32); function oneTokenCount() external view returns(uint256); function oneTokenAtIndex(uint256 index) external view returns(address); function isOneToken(address oneToken) external view returns(bool); // modules function moduleCount() external view returns(uint256); function moduleAtIndex(uint256 index) external view returns(address module); function isModule(address module) external view returns(bool); function isValidModuleType(address module, ModuleType moduleType) external view returns(bool); // foreign tokens function foreignTokenCount() external view returns(uint256); function foreignTokenAtIndex(uint256 index) external view returns(address); function foreignTokenInfo(address foreignToken) external view returns(bool collateral, uint256 oracleCount); function foreignTokenOracleCount(address foreignToken) external view returns(uint256); function foreignTokenOracleAtIndex(address foreignToken, uint256 index) external view returns(address); function isOracle(address foreignToken, address oracle) external view returns(bool); function isForeignToken(address foreignToken) external view returns(bool); function isCollateral(address foreignToken) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./IICHICommon.sol"; import "./IERC20Extended.sol"; interface IOneTokenV1Base is IICHICommon, IERC20 { function init(string memory name_, string memory symbol_, address oneTokenOracle_, address controller_, address mintMaster_, address memberToken_, address collateral_) external; function changeController(address controller_) external; function changeMintMaster(address mintMaster_, address oneTokenOracle) external; function addAsset(address token, address oracle) external; function removeAsset(address token) external; function setStrategy(address token, address strategy, uint256 allowance) external; function executeStrategy(address token) external; function removeStrategy(address token) external; function closeStrategy(address token) external; function increaseStrategyAllowance(address token, uint256 amount) external; function decreaseStrategyAllowance(address token, uint256 amount) external; function setFactory(address newFactory) external; function MODULE_TYPE() external view returns(bytes32); function oneTokenFactory() external view returns(address); function controller() external view returns(address); function mintMaster() external view returns(address); function memberToken() external view returns(address); function assets(address) external view returns(address, address); function balances(address token) external view returns(uint256 inVault, uint256 inStrategy); function collateralTokenCount() external view returns(uint256); function collateralTokenAtIndex(uint256 index) external view returns(address); function isCollateral(address token) external view returns(bool); function otherTokenCount() external view returns(uint256); function otherTokenAtIndex(uint256 index) external view returns(address); function isOtherToken(address token) external view returns(bool); function assetCount() external view returns(uint256); function assetAtIndex(uint256 index) external view returns(address); function isAsset(address token) external view returns(bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../oz_modified/ICHIOwnable.sol"; import "../oz_modified/ICHIInitializable.sol"; import "../interface/IERC20Extended.sol"; import "../interface/IICHICommon.sol"; contract ICHICommon is IICHICommon, ICHIOwnable, ICHIInitializable { uint256 constant PRECISION = 10 ** 18; uint256 constant INFINITE = uint256(0-1); address constant NULL_ADDRESS = address(0); // @dev internal fingerprints help prevent deployment-time governance errors bytes32 constant COMPONENT_CONTROLLER = keccak256(abi.encodePacked("ICHI V1 Controller")); bytes32 constant COMPONENT_VERSION = keccak256(abi.encodePacked("ICHI V1 OneToken Implementation")); bytes32 constant COMPONENT_STRATEGY = keccak256(abi.encodePacked("ICHI V1 Strategy Implementation")); bytes32 constant COMPONENT_MINTMASTER = keccak256(abi.encodePacked("ICHI V1 MintMaster Implementation")); bytes32 constant COMPONENT_ORACLE = keccak256(abi.encodePacked("ICHI V1 Oracle Implementation")); bytes32 constant COMPONENT_VOTERROLL = keccak256(abi.encodePacked("ICHI V1 VoterRoll Implementation")); bytes32 constant COMPONENT_FACTORY = keccak256(abi.encodePacked("ICHI OneToken Factory")); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "../_openzeppelin/token/ERC20/IERC20.sol"; interface IERC20Extended is IERC20 { function decimals() external view returns(uint8); function symbol() external view returns(string memory); function name() external view returns(string memory); } // 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 /** * @dev Constructor visibility has been removed from the original. * _transferOwnership() has been added to support proxied deployments. * Abstract tag removed from contract block. * Added interface inheritance and override modifiers. * Changed contract identifier in require error messages. */ pragma solidity >=0.6.0 <0.8.0; import "../_openzeppelin/utils/Context.sol"; import "../interface/IICHIOwnable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract ICHIOwnable is IICHIOwnable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "ICHIOwnable: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. * Ineffective for proxied deployed. Use initOwnable. */ constructor() { _transferOwnership(msg.sender); } /** @dev initialize proxied deployment */ function initOwnable() internal { require(owner() == address(0), "ICHIOwnable: already initialized"); _transferOwnership(msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual override returns (address) { return _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 override 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 override onlyOwner { _transferOwnership(newOwner); } /** * @dev be sure to call this in the initialization stage of proxied deployment or owner will not be set */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "ICHIOwnable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "../_openzeppelin/utils/Address.sol"; contract ICHIInitializable { bool private _initialized; bool private _initializing; modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "ICHIInitializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } modifier initialized { require(_initialized, "ICHIInitializable: contract is not initialized"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // 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); } } } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; library BitMath { // returns the 0 indexed position of the most significant bit of the input x // s.t. x >= 2**msb and x < 2**(msb+1) function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } // returns the 0 indexed position of the least significant bit of the input x // s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0) // i.e. the bit at the index is set and the mask of all lower bits is 0 function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::leastSignificantBit: zero'); r = 255; if (x & uint128(-1) > 0) { r -= 128; } else { x >>= 128; } if (x & uint64(-1) > 0) { r -= 64; } else { x >>= 64; } if (x & uint32(-1) > 0) { r -= 32; } else { x >>= 32; } if (x & uint16(-1) > 0) { r -= 16; } else { x >>= 16; } if (x & uint8(-1) > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; import './libraries/UQ112x112.sol'; import './interfaces/IUniswapV2Pair.sol'; import './interfaces/IUniswapV2Factory.sol'; import "./libraries/UniSafeMath.sol"; import "../../../_openzeppelin/token/ERC20/IERC20.sol"; contract UniswapV2Pair is IUniswapV2Pair { using UniSafeMath for uint256; using UQ112x112 for uint224; uint256 public constant MINIMUM_LIQUIDITY = 10 ** 3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public _token0; address public _token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public _price0CumulativeLast; uint256 public _price1CumulativeLast; uint256 public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event constructor() { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address __token0, address __token1) override external { require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check _token0 = __token0; _token1 = __token1; } function getReserves() override public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function token0() override external view returns (address){ return _token0; } function token1() override external view returns (address){ return _token1; } function price0CumulativeLast() override external view returns (uint256){ return _price0CumulativeLast; } function price1CumulativeLast() override external view returns (uint256){ return _price1CumulativeLast; } // update reserves and, on the first call per block, price accumulators function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired _price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; _price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // force reserves to match balances function sync() override external { _update(IERC20(_token0).balanceOf(address(this)), IERC20(_token1).balanceOf(address(this)), reserve0, reserve1); } } // SPDX-License-Identifier: GNU /** * @dev this contract is renamed to prevent conflict with oz while avoiding significant changes */ pragma solidity 0.7.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniswapSafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } } // SPDX-License-Identifier: ISC pragma solidity =0.7.6; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library UniSafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } }
library with helper methods for oracles that are concerned with computing average prices helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
library UniswapV2OracleLibrary { using FixedPoint for *; function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } function currentCumulativePrices( address pair ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { uint32 timeElapsed = blockTimestamp - blockTimestampLast; price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } function currentCumulativePrices( address pair ) internal view returns (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { uint32 timeElapsed = blockTimestamp - blockTimestampLast; price0Cumulative += uint256(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; price1Cumulative += uint256(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } }
1,106,246
[ 1, 12083, 598, 4222, 2590, 364, 578, 69, 9558, 716, 854, 356, 2750, 11748, 598, 20303, 8164, 19827, 4222, 445, 716, 1135, 326, 783, 1203, 2858, 3470, 326, 1048, 434, 2254, 1578, 16, 277, 18, 73, 18, 306, 20, 16, 576, 1578, 300, 404, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12083, 1351, 291, 91, 438, 58, 22, 23601, 9313, 288, 203, 565, 1450, 15038, 2148, 364, 380, 31, 203, 203, 203, 565, 445, 30610, 4921, 1435, 2713, 1476, 1135, 261, 11890, 1578, 13, 288, 203, 3639, 327, 2254, 1578, 12, 2629, 18, 5508, 738, 576, 2826, 3847, 1769, 203, 565, 289, 203, 203, 565, 445, 783, 39, 11276, 31862, 12, 203, 3639, 1758, 3082, 203, 565, 262, 2713, 1476, 1135, 261, 11890, 5034, 6205, 20, 39, 11276, 16, 2254, 5034, 6205, 21, 39, 11276, 16, 2254, 1578, 1203, 4921, 13, 288, 203, 3639, 1203, 4921, 273, 30610, 4921, 5621, 203, 3639, 6205, 20, 39, 11276, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 2934, 8694, 20, 39, 11276, 3024, 5621, 203, 3639, 6205, 21, 39, 11276, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 2934, 8694, 21, 39, 11276, 3024, 5621, 203, 203, 3639, 261, 11890, 17666, 20501, 20, 16, 2254, 17666, 20501, 21, 16, 2254, 1578, 1203, 4921, 3024, 13, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 2934, 588, 607, 264, 3324, 5621, 203, 3639, 309, 261, 2629, 4921, 3024, 480, 1203, 4921, 13, 288, 203, 5411, 2254, 1578, 813, 28827, 273, 1203, 4921, 300, 1203, 4921, 3024, 31, 203, 5411, 6205, 20, 39, 11276, 1011, 2254, 5034, 12, 7505, 2148, 18, 16744, 12, 455, 6527, 21, 16, 20501, 20, 2934, 67, 92, 13, 380, 813, 28827, 31, 203, 5411, 6205, 21, 39, 11276, 1011, 2254, 5034, 12, 7505, 2148, 18, 16744, 12, 2 ]
./full_match/43113/0x3dfe264d187CD8ae674c642C0De95F78EFC411DF/sources/OG.sol
* Initializes the contract. Sets token addresses, owner, and leftover token destination. Claiming period is not enabled. @param png_ the PNG token contract address @param owner_ the privileged contract owner @param remainderDestination_ address to transfer remaining PNG to when claiming ends. Should be community treasury./
) { require(owner_ != address(0), 'Airdrop::Construct: invalid new owner'); require(png_ != address(0), 'Airdrop::Construct: invalid png address'); airdropSupply = supply_; png = png_; owner = owner_; remainderDestination = remainderDestination_; }
7,208,749
[ 1, 9685, 326, 6835, 18, 11511, 1147, 6138, 16, 3410, 16, 471, 29709, 1147, 2929, 18, 18381, 310, 3879, 353, 486, 3696, 18, 225, 14476, 67, 326, 22476, 1147, 6835, 1758, 225, 3410, 67, 326, 11334, 2423, 6835, 3410, 225, 10022, 5683, 67, 1758, 358, 7412, 4463, 22476, 358, 1347, 377, 7516, 310, 3930, 18, 9363, 506, 19833, 9787, 345, 22498, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 288, 203, 3639, 2583, 12, 8443, 67, 480, 1758, 12, 20, 3631, 296, 37, 6909, 1764, 2866, 7249, 30, 2057, 394, 3410, 8284, 203, 3639, 2583, 12, 6446, 67, 480, 1758, 12, 20, 3631, 296, 37, 6909, 1764, 2866, 7249, 30, 2057, 14476, 1758, 8284, 203, 203, 3639, 279, 6909, 1764, 3088, 1283, 273, 14467, 67, 31, 203, 3639, 14476, 273, 14476, 67, 31, 203, 3639, 3410, 273, 3410, 67, 31, 203, 3639, 10022, 5683, 273, 10022, 5683, 67, 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 ]
./partial_match/1/0xe2A92856f6B5ac556Ac4a7eBCE63B72CBf9b22B1/sources/JackpotHandler.sol
why on Earth would you send ETH here? Don't.
payable(iCMON.getCh()).transfer(address(this).balance);
15,680,242
[ 1, 3350, 93, 603, 512, 27076, 4102, 1846, 1366, 512, 2455, 2674, 35, 7615, 1404, 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, 3639, 8843, 429, 12, 77, 9611, 673, 18, 588, 782, 1435, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 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 ]
./partial_match/1313161554/0xa200B567579a577F582d292f7A1b5C4ecce195F8/sources/Comptroller.sol
* @notice Set the given borrow caps for the given auToken markets. Borrowing that brings total borrows to or above borrow cap will revert. @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. @param auTokens The addresses of the markets (tokens) to change the borrow caps for @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing./
function _setMarketBorrowCaps(AuToken[] calldata auTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian"); uint numMarkets = auTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(auTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(auTokens[i], newBorrowCaps[i]); } }
16,936,474
[ 1, 694, 326, 864, 29759, 15788, 364, 326, 864, 20309, 1345, 2267, 2413, 18, 605, 15318, 310, 716, 5186, 899, 2078, 324, 280, 3870, 358, 578, 5721, 29759, 3523, 903, 15226, 18, 225, 7807, 578, 29759, 4664, 16709, 2779, 445, 358, 444, 326, 29759, 15788, 18, 432, 29759, 3523, 434, 374, 13955, 358, 640, 21325, 29759, 310, 18, 225, 20309, 5157, 1021, 6138, 434, 326, 2267, 2413, 261, 7860, 13, 358, 2549, 326, 29759, 15788, 364, 225, 394, 38, 15318, 24193, 1021, 394, 29759, 3523, 924, 316, 6808, 358, 506, 444, 18, 432, 460, 434, 374, 13955, 358, 640, 21325, 29759, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 542, 3882, 278, 38, 15318, 24193, 12, 37, 89, 1345, 8526, 745, 892, 20309, 5157, 16, 2254, 8526, 745, 892, 394, 38, 15318, 24193, 13, 3903, 288, 203, 377, 202, 6528, 12, 3576, 18, 15330, 422, 3981, 747, 1234, 18, 15330, 422, 29759, 4664, 16709, 2779, 16, 315, 3700, 3981, 578, 29759, 3523, 11026, 2779, 8863, 203, 203, 3639, 2254, 818, 3882, 2413, 273, 20309, 5157, 18, 2469, 31, 203, 3639, 2254, 818, 38, 15318, 24193, 273, 394, 38, 15318, 24193, 18, 2469, 31, 203, 203, 3639, 2583, 12, 2107, 3882, 2413, 480, 374, 597, 818, 3882, 2413, 422, 818, 38, 15318, 24193, 16, 315, 5387, 810, 8863, 203, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 818, 3882, 2413, 31, 277, 27245, 288, 203, 5411, 29759, 24193, 63, 2867, 12, 8377, 5157, 63, 77, 5717, 65, 273, 394, 38, 15318, 24193, 63, 77, 15533, 203, 5411, 3626, 1166, 38, 15318, 4664, 12, 8377, 5157, 63, 77, 6487, 394, 38, 15318, 24193, 63, 77, 19226, 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 ]
./partial_match/56/0x856D781fFafa4CD2464aa267f0692edAA9175Ec5/sources/MasterChef.sol
Safe SUB transfer function, just in case if rounding error causes pool to not have enough SUB.
function safeSUBTransfer(address _to, uint256 _amount) internal { uint256 SUBBal = SUB.balanceOf(address(this)); if (_amount > SUBBal) { SUB.transfer(_to, SUBBal); SUB.transfer(_to, _amount); } }
11,215,634
[ 1, 9890, 10025, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 10025, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 8362, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 10025, 38, 287, 273, 10025, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 8949, 405, 10025, 38, 287, 13, 288, 203, 5411, 10025, 18, 13866, 24899, 869, 16, 10025, 38, 287, 1769, 203, 5411, 10025, 18, 13866, 24899, 869, 16, 389, 8949, 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 ]
./full_match/1/0x85578D91DAC3Fe97dd31206A9779654bE3ae9365/sources/tests/newFile_test.sol
Use 'Assert' methods: https:remix-ide.readthedocs.io/en/latest/assert_library.html Assert.ok(2 == 2, 'should be true'); Assert.greaterThan(uint(2), uint(1), "2 should be greater than to 1"); Assert.lesserThan(uint(2), uint(3), "2 should be lesser than to 3");
function checkSuccess() public { }
3,116,284
[ 1, 3727, 296, 8213, 11, 2590, 30, 2333, 30, 2764, 697, 17, 831, 18, 25254, 329, 22280, 18, 1594, 19, 275, 19, 13550, 19, 11231, 67, 12083, 18, 2620, 5452, 18, 601, 12, 22, 422, 576, 16, 296, 13139, 506, 638, 8284, 5452, 18, 11556, 2045, 9516, 12, 11890, 12, 22, 3631, 2254, 12, 21, 3631, 315, 22, 1410, 506, 6802, 2353, 358, 404, 8863, 5452, 18, 2656, 264, 9516, 12, 11890, 12, 22, 3631, 2254, 12, 23, 3631, 315, 22, 1410, 506, 5242, 264, 2353, 358, 890, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 866, 4510, 1435, 1071, 288, 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, -100, -100 ]
pragma solidity ^0.4.18; // Test contract to test against reentrancy in the case where a payment contract is payable and requires contract TestRequestPaymentStuckRevert { function () public payable { // solium-disable-next-line error-reason require(false); } }
solium-disable-next-line error-reason
{ require(false); }
13,053,884
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 555, 17, 10579, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 2583, 12, 5743, 1769, 203, 565, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/ERC20Capped.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20Capped is ERC20 { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ChickenToken.sol pragma solidity 0.6.12; // ChickenToken with Governance. Capped at 580,000,000 supply. contract ChickenToken is ERC20Capped, Ownable { constructor() public ERC20("ChickenToken", "CHKN") ERC20Capped(580000000000000000000000000) { } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (FryCook). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "CHKN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "CHKN::delegateBySig: invalid nonce"); require(now <= expiry, "CHKN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CHKN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CHKNs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "CHKN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/FryCook.sol pragma solidity 0.6.12; // An interface for a future component of the CHKN system, allowing migration // from one type of LP token to another. Migration moves liquidity from an exchange // contract to another, e.g. for a swap version update. All users keep their // staked liquidity and can deposit or withdraw the new type of token // (kept in the same pool / pid) afterwards. interface ICookMigrator { // Perform LP token migration from UniswapV2 to ChickenFarm. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to UniswapV2 LP tokens. // ChickenFarm must mint EXACTLY the same amount of ChickenFarm LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // FryCook works the fryer. They make some good chicken! // // Note that there is an EXECUTIVE_ROLE and the executive(s) wields tremendous // power. The deployer will have executive power until initial setup is complete, // then renounce that direct power in favor of Timelocked control so the community // can see incoming executive orders (including role changes). Eventually, this // setup will be replaced with community governance by CHKN token holders. // // Executives determine who holds other roles and set contract references // (e.g. for migration). The other roles are: // // Head Chef: Designs the menu (can add and update lp token pools) // Sous Chef: Tweaks recipes (can update lp token pool allocation points) // Waitstaff: Carries orders and payments (can deposit / withdraw on behalf of stakers) // // It makes sense for an executive (individual or community) to also operate as the // head chef, but nothing but a well-tested and audited smart contract should EVER be assigned // to waitstaff. Waitstaff have full access to all staked tokens. contract FryCook is AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKNs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKNs distribution occurs. uint256 totalScore; // Total score of all investors. uint256 accChickenPerScore; // Accumulated CHKNs per score, times 1e12. See below. // early bird point rewards (larger share of CHKN mints w/in the pool) uint256 earlyBirdMinShares; uint256 earlyBirdExtra; uint256 earlyBirdGraceEndBlock; uint256 earlyBirdHalvingBlocks; } // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 score; // The staked "score" based on LP tokens and early bird bonus uint256 earlyBirdMult; // Early bird bonus multiplier, scaled by EARLY_BIRD_PRECISION bool earlyBird; // Does the score include an early bird bonus? uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKNs // entitled to a user but is pending to be distributed is: // // pending reward = (user.score * pool.accChickenPerScore) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChickenPerScore` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` and `score` gets updated. // 4. User's `rewardDebt` gets updated. } // Access Control Roles. This is the FryCook, but there's other jobs in the kitchen. bytes32 public constant EXECUTIVE_ROLE = keccak256("EXECUTIVE_ROLE"); // aka owner: determines other roles bytes32 public constant HEAD_CHEF_ROLE = keccak256("HEAD_CHEF_ROLE"); // governance: token pool changes, control over agent list bytes32 public constant SOUS_CHEF_ROLE = keccak256("SOUS_CHEF_ROLE"); // pool spiciness tweaks: can change allocation points for pools bytes32 public constant WAITSTAFF_ROLE = keccak256("WAITSTAFF_ROLE"); // token agent(s): can make deposits / withdrawals on behalf of stakers // The CHKN TOKEN! ChickenToken public chicken; uint256 public chickenCap; // Dev address. address public devaddr; // Block number when bonus CHKN stage ends (staged decline to no bonus). uint256 public bonusStage2Block; uint256 public bonusStage3Block; uint256 public bonusStage4Block; uint256 public bonusEndBlock; // CHKN tokens created per block. uint256 public chickenPerBlock; // Bonus muliplier for early chicken makers. uint256 public constant BONUS_MULTIPLIER_STAGE_1 = 20; uint256 public constant BONUS_MULTIPLIER_STAGE_2 = 15; uint256 public constant BONUS_MULTIPLIER_STAGE_3 = 10; uint256 public constant BONUS_MULTIPLIER_STAGE_4 = 5; // Block number when dev share declines (staged decline to lowest share). uint256 public devBonusStage2Block; uint256 public devBonusStage3Block; uint256 public devBonusStage4Block; uint256 public devBonusEndBlock; // Dev share divisor for each bonus stage. uint256 public constant DEV_DIV_STAGE_1 = 10; // 10% uint256 public constant DEV_DIV_STAGE_2 = 12; // 8.333..% uint256 public constant DEV_DIV_STAGE_3 = 16; // 6.25% uint256 public constant DEV_DIV_STAGE_4 = 25; // 4% uint256 public constant DEV_DIV = 50; // 2% // Precision values uint256 public constant EARLY_BIRD_PRECISION = 1e12; uint256 public constant ACC_CHICKEN_PRECISION = 1e12; // The migrator contract. It has a lot of power. Can only be set through governance (owner). ICookMigrator public migrator; // Info of each pool. PoolInfo[] public poolInfo; mapping (address => uint256) public tokenPid; mapping (address => bool) public hasToken; // 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 CHKN mining starts. uint256 public startBlock; event Deposit(address indexed staker, address indexed funder, uint256 indexed pid, uint256 amount); event Withdraw(address indexed staker, address indexed agent, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ChickenToken _chicken, address _devaddr, uint256 _chickenPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _devBonusEndBlock ) public { chicken = _chicken; devaddr = _devaddr; chickenPerBlock = _chickenPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; devBonusEndBlock = _devBonusEndBlock; // calculate mint bonus stage blocks (block-of-transition from 20x to 15x, etc.) uint256 bonusStep = bonusEndBlock.sub(startBlock).div(4); bonusStage2Block = bonusStep.add(startBlock); bonusStage3Block = bonusStep.mul(2).add(startBlock); bonusStage4Block = bonusStep.mul(3).add(startBlock); // calculate dev divisor stage blocks uint256 devBonusStep = devBonusEndBlock.sub(startBlock).div(4); devBonusStage2Block = devBonusStep.add(startBlock); devBonusStage3Block = devBonusStep.mul(2).add(startBlock); devBonusStage4Block = devBonusStep.mul(3).add(startBlock); // set up initial roles (caller is owner and manager). The caller // CANNOT act as waitstaff; athough they can add and modify pools, // they CANNOT touch user deposits. Nothing but another smart contract // should ever be waitstaff. _setupRole(EXECUTIVE_ROLE, msg.sender); // can manage other roles and link contracts _setupRole(HEAD_CHEF_ROLE, msg.sender); // can create and alter pools // set up executives as role administrators. // after initial setup, all roles are expected to be served by other contracts // (e.g. Timelock, GovernorAlpha, etc.) _setRoleAdmin(EXECUTIVE_ROLE, EXECUTIVE_ROLE); _setRoleAdmin(HEAD_CHEF_ROLE, EXECUTIVE_ROLE); _setRoleAdmin(SOUS_CHEF_ROLE, EXECUTIVE_ROLE); _setRoleAdmin(WAITSTAFF_ROLE, EXECUTIVE_ROLE); // store so we never have to query again chickenCap = chicken.cap(); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by a manager. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, uint256 _earlyBirdMinShares, uint256 _earlyBirdInitialBonus, uint256 _earlyBirdGraceEndBlock, uint256 _earlyBirdHalvingBlocks, bool _withUpdate ) public { require(hasRole(HEAD_CHEF_ROLE, msg.sender), "FryCook::add: not authorized"); require(!hasToken[address(_lpToken)], "FryCook::add: lpToken already added"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); hasToken[address(_lpToken)] = true; tokenPid[address(_lpToken)] = poolInfo.length; poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, earlyBirdMinShares: _earlyBirdMinShares, earlyBirdExtra: _earlyBirdInitialBonus.sub(1), // provided as multiplier: 100x. Declines to 1x, so "99" extra. earlyBirdGraceEndBlock: _earlyBirdGraceEndBlock, earlyBirdHalvingBlocks: _earlyBirdHalvingBlocks, lastRewardBlock: lastRewardBlock, totalScore: 0, accChickenPerScore: 0 })); } // Update the given pool's CHKN allocation point. Can only be called by a manager. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public { require(hasRole(HEAD_CHEF_ROLE, msg.sender) || hasRole(SOUS_CHEF_ROLE, msg.sender), "FryCook::set: not authorized"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by a manager. function setMigrator(ICookMigrator _migrator) public { require(hasRole(EXECUTIVE_ROLE, msg.sender), "FryCook::setMigrator: not authorized"); 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) public { require(address(migrator) != address(0), "FryCook::migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "FryCook::migrate: bad"); pool.lpToken = newLpToken; tokenPid[address(newLpToken)] = _pid; hasToken[address(newLpToken)] = true; tokenPid[address(lpToken)] = 0; hasToken[address(lpToken)] = false; } // Return the number of blocks intersecting between the two ranges. // Assumption: _from <= _to, _from2 <= _to2. function getIntersection(uint256 _from, uint256 _to, uint256 _from2, uint256 _to2) public pure returns (uint256) { if (_to <= _from2) { return 0; } else if (_to2 <= _from) { return 0; } else { return Math.min(_to, _to2).sub(Math.max(_from, _from2)); } } // Return CHKN reward (mint) multiplier over the given range, _from to _to block. // Multiply against chickenPerBlock to determine the total amount minted // during that time (not including devaddr share). Ignores "startBlock". // Assumption: _from <= _to. Otherwise get weird results. function getMintMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_from >= bonusEndBlock) { // no bonus return _to.sub(_from); } else { // potentially intersect four bonus periods and/or "no bonus" uint256 mult = 0; mult = mult.add(getIntersection(_from, _to, 0, bonusStage2Block).mul(BONUS_MULTIPLIER_STAGE_1)); mult = mult.add(getIntersection(_from, _to, bonusStage2Block, bonusStage3Block).mul(BONUS_MULTIPLIER_STAGE_2)); mult = mult.add(getIntersection(_from, _to, bonusStage3Block, bonusStage4Block).mul(BONUS_MULTIPLIER_STAGE_3)); mult = mult.add(getIntersection(_from, _to, bonusStage4Block, bonusEndBlock).mul(BONUS_MULTIPLIER_STAGE_4)); mult = mult.add(Math.max(_to, bonusEndBlock).sub(bonusEndBlock)); // known: _from < bonusEndBlock return mult; } } // Returns the divisor to determine the developer's share of coins at the // given block. For M coins minted, dev gets M.div(_val_). For a block range, // undershoot by providing _to block (dev gets up to, not over, the bonus amount). function getDevDivisor(uint256 _block) public view returns (uint256) { if (_block >= devBonusEndBlock) { return DEV_DIV; } else if (_block >= devBonusStage4Block) { return DEV_DIV_STAGE_4; } else if (_block >= devBonusStage3Block) { return DEV_DIV_STAGE_3; } else if (_block >= devBonusStage2Block) { return DEV_DIV_STAGE_2; } else { return DEV_DIV_STAGE_1; } } // Returns the score multiplier for an early bird investor who qualifies // at _block for _pid. The investment quantity and min threshold are not // checked; qualification is a precondition. // The output is scaled by EARLY_BIRD_PRECISION; e.g. a return value of // 1.5 * EARLY_BIRD_PRECISION indicates a multiplier of 1.5x. function getEarlyBirdMultiplier(uint256 _block, uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; uint256 decliningPortion = pool.earlyBirdExtra.mul(EARLY_BIRD_PRECISION); if (_block <= pool.earlyBirdGraceEndBlock) { return decliningPortion.add(EARLY_BIRD_PRECISION); } uint256 distance = _block.sub(pool.earlyBirdGraceEndBlock); uint256 halvings = distance.div(pool.earlyBirdHalvingBlocks); // whole number if (halvings >= 120) { // asymptotic, up to a point return EARLY_BIRD_PRECISION; // 1x } // approximate exponential decay with linear interpolation between integer exponents uint256 progress = distance.sub(halvings.mul(pool.earlyBirdHalvingBlocks)); uint256 divisor = (2 ** halvings).mul(1e8); // scaled once for precision uint256 nextDivisor = (2 ** (halvings.add(1))).mul(1e8); // scaled once for precision uint256 diff = nextDivisor.sub(divisor); uint256 alpha = progress.mul(1e8).div(pool.earlyBirdHalvingBlocks); // scaled once for precision divisor = divisor.add(diff.mul(alpha).div(1e8)); // unscale alpha after mult. to keep precision // divisor is scaled up; scale up declining portion by same amount before division return decliningPortion.mul(1e8).div(divisor).add(EARLY_BIRD_PRECISION); } // View function to see pending CHKNs on frontend. function pendingChicken(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChickenPerScore = pool.accChickenPerScore; uint256 totalScore = pool.totalScore; if (block.number > pool.lastRewardBlock && totalScore != 0) { uint256 multiplier = getMintMultiplier(pool.lastRewardBlock, block.number); uint256 chickenReward = multiplier.mul(chickenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accChickenPerScore = accChickenPerScore.add(chickenReward.mul(ACC_CHICKEN_PRECISION).div(totalScore)); } return user.score.mul(accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 totalScore = pool.totalScore; if (totalScore == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMintMultiplier(pool.lastRewardBlock, block.number); uint256 chickenReward = multiplier.mul(chickenPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 devReward = chickenReward.div(getDevDivisor(block.number)); uint256 supply = chicken.totalSupply(); // safe mint: don't exceed supply if (supply.add(chickenReward).add(devReward) > chickenCap) { chickenReward = chickenCap.sub(supply); devReward = 0; } chicken.mint(address(this), chickenReward); chicken.mint(devaddr, devReward); pool.accChickenPerScore = pool.accChickenPerScore.add(chickenReward.mul(ACC_CHICKEN_PRECISION).div(totalScore)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to FryCook for CHKN allocation. Deposit 0 to bump a pool update. function deposit(uint256 _pid, uint256 _amount) public { _deposit(_pid, _amount, msg.sender, msg.sender); } // Deposit LP tokens on behalf of another user. function depositTo(uint256 _pid, uint256 _amount, address _staker) public { require(hasRole(WAITSTAFF_ROLE, msg.sender), "FryCook::depositTo: not authorized"); _deposit(_pid, _amount, _staker, msg.sender); } // Handle deposits, whether agent-driven or user-initiated. function _deposit(uint256 _pid, uint256 _amount, address _staker, address _funder) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_staker]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt); if (pending > 0) { safeChickenTransfer(_staker, pending); } } else { user.earlyBirdMult = EARLY_BIRD_PRECISION; // equiv. to 1x } // transfer LP tokens; update user info if (_amount > 0) { pool.lpToken.safeTransferFrom(_funder, address(this), _amount); uint256 oldScore = user.score; user.amount = user.amount.add(_amount); if (!user.earlyBird && user.amount >= pool.earlyBirdMinShares) { user.earlyBird = true; user.earlyBirdMult = getEarlyBirdMultiplier(block.number, _pid); // scaled } user.score = user.amount.mul(user.earlyBirdMult).div(EARLY_BIRD_PRECISION); // unscale pool.totalScore = pool.totalScore.add(user.score).sub(oldScore); } // update dept regardless of whether score changes or deposit is > 0 user.rewardDebt = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION); emit Deposit(_staker, _funder, _pid, _amount); } // Withdraw staked LP tokens from FryCook. Also transfers pending chicken. function withdraw(uint256 _pid, uint256 _amount) public { _withdraw(_pid, _amount, address(msg.sender), address(msg.sender)); } // Withdraw a user's staked LP tokens as an agent. Also transfers pending // chicken (to the staking user, NOT the agent). function withdrawFrom(uint256 _pid, uint256 _amount, address _staker) public { require(hasRole(WAITSTAFF_ROLE, msg.sender), "FryCook::withdrawFrom: not authorized"); _withdraw(_pid, _amount, _staker, address(msg.sender)); } // Withdraw LP tokens from FryCook to the agent. Staked chicken // goes to the _staker. We don't support deferred CHKN transfers; every time // a deposit or withdrawal happens, pending CHKN must be transferred or // the books aren't kept clean. function _withdraw(uint256 _pid, uint256 _amount, address _staker, address _agent) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_staker]; require(user.amount >= _amount, "FryCook::withdraw: not good"); updatePool(_pid); uint256 pending = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION).sub(user.rewardDebt); if (pending > 0) { safeChickenTransfer(_staker, pending); } // update user info if (_amount > 0) { uint256 oldScore = user.score; user.amount = user.amount.sub(_amount); if (user.earlyBird && user.amount < pool.earlyBirdMinShares) { user.earlyBird = false; user.earlyBirdMult = EARLY_BIRD_PRECISION; } user.score = user.amount.mul(user.earlyBirdMult).div(EARLY_BIRD_PRECISION); // unscale pool.lpToken.safeTransfer(_agent, _amount); pool.totalScore = pool.totalScore.add(user.score).sub(oldScore); } // update reward debt regardless of whether score changed, since debt may have user.rewardDebt = user.score.mul(pool.accChickenPerScore).div(ACC_CHICKEN_PRECISION); emit Withdraw(_staker, _agent, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); pool.totalScore = pool.totalScore.sub(user.score); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.earlyBird = false; user.earlyBirdMult = EARLY_BIRD_PRECISION; user.score = 0; user.rewardDebt = 0; } // Safe chicken transfer function, just in case if rounding error causes pool to not have enough CHKNs. function safeChickenTransfer(address _to, uint256 _amount) internal { uint256 chickenBal = chicken.balanceOf(address(this)); if (_amount > chickenBal) { chicken.transfer(_to, chickenBal); } else { chicken.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "FryCook::dev: wut?"); devaddr = _devaddr; } }
asymptotic, up to a point
if (halvings >= 120) {
14,410,108
[ 1, 345, 2942, 337, 352, 335, 16, 731, 358, 279, 1634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 22314, 90, 899, 1545, 15743, 13, 288, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.10; library FTSU { struct MerkleProof { bytes32 label; // the hash value of the sibling uint posIden; // the binary bit indicating the position } // functions for signature verification function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s){ require(sig.length == 65); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address){ (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig); return ecrecover(message, v, r, s); } function prefixed(bytes32 hash) internal pure returns (bytes32){ return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
functions for signature verification
function splitSignature(bytes memory sig) internal pure returns (uint8 v, bytes32 r, bytes32 s){ require(sig.length == 65); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } return (v, r, s); }
1,752,917
[ 1, 10722, 364, 3372, 11805, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 1416, 5374, 12, 3890, 3778, 3553, 13, 2713, 16618, 1135, 261, 11890, 28, 331, 16, 1731, 1578, 436, 16, 1731, 1578, 272, 15329, 203, 3639, 2583, 12, 7340, 18, 2469, 422, 15892, 1769, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 12, 7340, 16, 3847, 3719, 203, 5411, 272, 519, 312, 945, 12, 1289, 12, 7340, 16, 5178, 3719, 203, 5411, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 7340, 16, 19332, 20349, 203, 3639, 289, 203, 3639, 327, 261, 90, 16, 436, 16, 272, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xA1F18e3E99976AdA8F598458c6c0dc0b5c713Db4/sources/contracts/ERC721ACMUpgradeable.sol
old _addressData slotslither-disable-next-line constable-states
uint256 private _emptySlot;
3,075,776
[ 1, 1673, 389, 2867, 751, 4694, 2069, 2927, 17, 8394, 17, 4285, 17, 1369, 1866, 429, 17, 7992, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 3238, 389, 5531, 8764, 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 ]
./partial_match/56/0x1Ba50fB34360143b4006d8Bb803485D2D1837bB3/sources/Digihats.sol
* @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)); require(!_exists(tokenId)); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); }
11,055,936
[ 1, 49, 28142, 1375, 2316, 548, 68, 471, 29375, 518, 358, 1375, 869, 8338, 9744, 30, 10858, 434, 333, 707, 353, 19169, 477, 11349, 16, 999, 288, 67, 4626, 49, 474, 97, 17334, 3323, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 486, 1005, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 7377, 1282, 279, 288, 5912, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 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, 10019, 203, 3639, 2583, 12, 5, 67, 1808, 12, 2316, 548, 10019, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 4505, 5157, 63, 869, 8009, 1289, 12, 2316, 548, 1769, 203, 203, 3639, 389, 2316, 5460, 414, 18, 542, 12, 2316, 548, 16, 358, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xFe6667986f58F2F7ed1e7C17Cee3951d8ABb717f/sources/contracts/RedPacket.sol
passcode hash of red packet
uint256 passcodeHash;
16,584,323
[ 1, 5466, 710, 1651, 434, 1755, 4414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1342, 710, 2310, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.5; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ /// @notice Implementation of [EIP-1167] based on [clone-factory] /// source code. /// /// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167 // Original implementation: https://github.com/optionality/clone-factory // Modified to use ^0.8.5; instead of ^0.4.23 solidity version. /* solhint-disable no-inline-assembly */ abstract contract CloneFactory { /// @notice Creates EIP-1167 clone of the contract under the provided /// `target` address. Returns address of the created clone. /// @dev In specific circumstances, such as the `target` contract destroyed, /// create opcode may return 0x0 address. The code calling this /// function should handle this corner case properly. function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } /// @notice Checks if the contract under the `query` address is a EIP-1167 /// clone of the contract under `target` address. function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IERC20WithPermit.sol"; import "./IReceiveApproval.sol"; /// @title ERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. contract ERC20WithPermit is IERC20WithPermit, Ownable { /// @notice The amount of tokens owned by the given account. mapping(address => uint256) public override balanceOf; /// @notice The remaining number of tokens that spender will be /// allowed to spend on behalf of owner through `transferFrom` and /// `burnFrom`. This is zero by default. mapping(address => mapping(address => uint256)) public override allowance; /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. mapping(address => uint256) public override nonces; uint256 public immutable cachedChainId; bytes32 public immutable cachedDomainSeparator; /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. bytes32 public constant override PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); /// @notice The amount of tokens in existence. uint256 public override totalSupply; /// @notice The name of the token. string public override name; /// @notice The symbol of the token. string public override symbol; /// @notice The decimals places of the token. uint8 public constant override decimals = 18; constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; cachedChainId = block.chainid; cachedDomainSeparator = buildDomainSeparator(); } /// @notice Moves `amount` tokens from the caller's account to `recipient`. /// @return True if the operation succeeded, reverts otherwise. /// @dev Requirements: /// - `recipient` cannot be the zero address, /// - the caller must have a balance of at least `amount`. function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /// @notice Moves `amount` tokens from `sender` to `recipient` using the /// allowance mechanism. `amount` is then deducted from the caller's /// allowance unless the allowance was made for `type(uint256).max`. /// @return True if the operation succeeded, reverts otherwise. /// @dev 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 ) external override returns (bool) { uint256 currentAllowance = allowance[sender][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Transfer amount exceeds allowance" ); _approve(sender, msg.sender, currentAllowance - amount); } _transfer(sender, recipient, amount); return true; } /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. If the `amount` is set /// to `type(uint256).max` then `transferFrom` and `burnFrom` will /// not reduce an allowance. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { /* solhint-disable-next-line not-rely-on-time */ require(deadline >= block.timestamp, "Permission expired"); // Validate `s` and `v` values for a malleability concern described in EIP2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order and `v` value of 27 or 28 are considered valid. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid signature 's' value" ); require(v == 27 || v == 28, "Invalid signature 'v' value"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature" ); _approve(owner, spender, amount); } /// @notice Creates `amount` tokens and assigns them to `account`, /// increasing the total supply. /// @dev Requirements: /// - `recipient` cannot be the zero address. function mint(address recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Mint to the zero address"); beforeTokenTransfer(address(0), recipient, amount); totalSupply += amount; balanceOf[recipient] += amount; emit Transfer(address(0), recipient, amount); } /// @notice Destroys `amount` tokens from the caller. /// @dev Requirements: /// - the caller must have a balance of at least `amount`. function burn(uint256 amount) external override { _burn(msg.sender, amount); } /// @notice Destroys `amount` of tokens from `account` using the allowance /// mechanism. `amount` is then deducted from the caller's allowance /// unless the allowance was made for `type(uint256).max`. /// @dev Requirements: /// - `account` must have a balance of at least `amount`, /// - the caller must have allowance for `account`'s tokens of at least /// `amount`. function burnFrom(address account, uint256 amount) external override { uint256 currentAllowance = allowance[account][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Burn amount exceeds allowance" ); _approve(account, msg.sender, currentAllowance - amount); } _burn(account, amount); } /// @notice Calls `receiveApproval` function on spender previously approving /// the spender to withdraw from the caller multiple times, up to /// the `amount` amount. If this function is called again, it /// overwrites the current allowance with `amount`. Reverts if the /// approval reverted or if `receiveApproval` call on the spender /// reverted. /// @return True if both approval and `receiveApproval` calls succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external override returns (bool) { if (approve(spender, amount)) { IReceiveApproval(spender).receiveApproval( msg.sender, amount, address(this), extraData ); return true; } return false; } /// @notice Sets `amount` as the allowance of `spender` over the caller's /// tokens. /// @return True if the operation succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. /// 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 function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() public view override returns (bytes32) { // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the // chainId and is defined at contract deployment instead of // reconstructed for every signature, there is a risk of possible replay // attacks between chains in the event of a future chain split. // To address this issue, we check the cached chain ID against the // current one and in case they are different, we build domain separator // from scratch. if (block.chainid == cachedChainId) { return cachedDomainSeparator; } else { return buildDomainSeparator(); } } /// @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. // slither-disable-next-line dead-code function beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _burn(address account, uint256 amount) internal { uint256 currentBalance = balanceOf[account]; require(currentBalance >= amount, "Burn amount exceeds balance"); beforeTokenTransfer(account, address(0), amount); balanceOf[account] = currentBalance - amount; totalSupply -= amount; emit Transfer(account, address(0), amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "Transfer from the zero address"); require(recipient != address(0), "Transfer to the zero address"); require(recipient != address(this), "Transfer to the token address"); beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = balanceOf[sender]; require(senderBalance >= amount, "Transfer amount exceeds balance"); balanceOf[sender] = senderBalance - amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "Approve from the zero address"); require(spender != address(0), "Approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } function buildDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by tokens supporting /// `approveAndCall`/`receiveApproval` pattern. interface IApproveAndCall { /// @notice Executes `receiveApproval` function on spender as specified in /// `IReceiveApproval` interface. Approves spender to withdraw from /// the caller multiple times, up to the `amount`. If this /// function is called again, it overwrites the current allowance /// with `amount`. Reverts if the approval reverted or if /// `receiveApproval` call on the spender reverted. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IApproveAndCall.sol"; /// @title IERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. interface IERC20WithPermit is IERC20, IERC20Metadata, IApproveAndCall { /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @notice Destroys `amount` tokens from the caller. function burn(uint256 amount) external; /// @notice Destroys `amount` of tokens from `account`, deducting the amount /// from caller's allowance. function burnFrom(address account, uint256 amount) external; /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. function nonces(address owner) external view returns (uint256); /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. /* solhint-disable-next-line func-name-mixedcase */ function PERMIT_TYPEHASH() external pure returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by contracts supporting /// `approveAndCall`/`receiveApproval` pattern. interface IReceiveApproval { /// @notice Receives approval to spend tokens. Called as a result of /// `approveAndCall` call on the token. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPool.sol"; import "./interfaces/IAssetPoolUpgrade.sol"; import "./RewardsPool.sol"; import "./UnderwriterToken.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Asset Pool /// @notice Asset pool is a component of a Coverage Pool. Asset Pool /// accepts a single ERC20 token as collateral, and returns an /// underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. contract AssetPool is Ownable, IAssetPool { using SafeERC20 for IERC20; using SafeERC20 for UnderwriterToken; IERC20 public immutable collateralToken; UnderwriterToken public immutable underwriterToken; RewardsPool public immutable rewardsPool; IAssetPoolUpgrade public newAssetPool; /// @notice The time it takes the underwriter to withdraw their collateral /// and rewards from the pool. This is the time that needs to pass /// between initiating and completing the withdrawal. During that /// time, underwriter is still earning rewards and their share of /// the pool is still a subject of a possible coverage claim. uint256 public withdrawalDelay = 21 days; uint256 public newWithdrawalDelay; uint256 public withdrawalDelayChangeInitiated; /// @notice The time the underwriter has after the withdrawal delay passed /// to complete the withdrawal. During that time, underwriter is /// still earning rewards and their share of the pool is still /// a subject of a possible coverage claim. /// After the withdrawal timeout elapses, tokens stay in the pool /// and the underwriter has to initiate the withdrawal again and /// wait for the full withdrawal delay to complete the withdrawal. uint256 public withdrawalTimeout = 2 days; uint256 public newWithdrawalTimeout; uint256 public withdrawalTimeoutChangeInitiated; mapping(address => uint256) public withdrawalInitiatedTimestamp; mapping(address => uint256) public pendingWithdrawal; event Deposited( address indexed underwriter, uint256 amount, uint256 covAmount ); event CoverageClaimed( address indexed recipient, uint256 amount, uint256 timestamp ); event WithdrawalInitiated( address indexed underwriter, uint256 covAmount, uint256 timestamp ); event WithdrawalCompleted( address indexed underwriter, uint256 amount, uint256 covAmount, uint256 timestamp ); event ApprovedAssetPoolUpgrade(address newAssetPool); event CancelledAssetPoolUpgrade(address cancelledAssetPool); event AssetPoolUpgraded( address indexed underwriter, uint256 collateralAmount, uint256 covAmount, uint256 timestamp ); event WithdrawalDelayUpdateStarted( uint256 withdrawalDelay, uint256 timestamp ); event WithdrawalDelayUpdated(uint256 withdrawalDelay); event WithdrawalTimeoutUpdateStarted( uint256 withdrawalTimeout, uint256 timestamp ); event WithdrawalTimeoutUpdated(uint256 withdrawalTimeout); /// @notice Reverts if the withdrawal governance delay has not passed yet or /// if the change was not yet initiated. /// @param changeInitiatedTimestamp The timestamp at which the change has /// been initiated modifier onlyAfterWithdrawalGovernanceDelay( uint256 changeInitiatedTimestamp ) { require(changeInitiatedTimestamp > 0, "Change not initiated"); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - changeInitiatedTimestamp >= withdrawalGovernanceDelay(), "Governance delay has not elapsed" ); _; } constructor( IERC20 _collateralToken, UnderwriterToken _underwriterToken, address rewardsManager ) { collateralToken = _collateralToken; underwriterToken = _underwriterToken; rewardsPool = new RewardsPool( _collateralToken, address(this), rewardsManager ); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// Optional data in extraData may include a minimal amount of /// underwriter tokens expected to be minted for a depositor. There /// are cases when an amount of minted tokens matters for a /// depositor, as tokens might be used in third party exchanges. /// @dev This function is a shortcut for approve + deposit. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external { require(msg.sender == token, "Only token caller allowed"); require( token == address(collateralToken), "Unsupported collateral token" ); uint256 toMint = _calculateTokensToMint(amount); if (extraData.length != 0) { require(extraData.length == 32, "Unexpected data length"); uint256 minAmountToMint = abi.decode(extraData, (uint256)); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); } _deposit(from, amount, toMint); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @return The amount of minted underwriter tokens function deposit(uint256 amountToDeposit) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @param minAmountToMint Underwriter minimal tokens amount that a user /// expects to receive in exchange for the deposited /// collateral tokens /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Initiates the withdrawal of collateral and rewards from the /// pool. Must be followed with completeWithdrawal call after the /// withdrawal delay passes. Accepts the amount of underwriter /// tokens representing the share of the pool that should be /// withdrawn. Can be called multiple times increasing the pool share /// to withdraw and resetting the withdrawal initiated timestamp for /// each call. Can be called with 0 covAmount to reset the /// withdrawal initiated timestamp if the underwriter has a pending /// withdrawal. In practice 0 covAmount should be used only to /// initiate the withdrawal again in case one did not complete the /// withdrawal before the withdrawal timeout elapsed. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external override { uint256 pending = pendingWithdrawal[msg.sender]; require( covAmount > 0 || pending > 0, "Underwriter token amount must be greater than 0" ); pending += covAmount; pendingWithdrawal[msg.sender] = pending; /* solhint-disable not-rely-on-time */ withdrawalInitiatedTimestamp[msg.sender] = block.timestamp; emit WithdrawalInitiated(msg.sender, pending, block.timestamp); /* solhint-enable not-rely-on-time */ if (covAmount > 0) { underwriterToken.safeTransferFrom( msg.sender, address(this), covAmount ); } } /// @notice Completes the previously initiated withdrawal for the /// underwriter. Anyone can complete the withdrawal for the /// underwriter. The withdrawal has to be completed before the /// withdrawal timeout elapses. Otherwise, the withdrawal has to /// be initiated again and the underwriter has to wait for the /// entire withdrawal delay again before being able to complete /// the withdrawal. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external override returns (uint256) { /* solhint-disable not-rely-on-time */ uint256 initiatedAt = withdrawalInitiatedTimestamp[underwriter]; require(initiatedAt > 0, "No withdrawal initiated for the underwriter"); uint256 withdrawalDelayEndTimestamp = initiatedAt + withdrawalDelay; require( withdrawalDelayEndTimestamp < block.timestamp, "Withdrawal delay has not elapsed" ); require( withdrawalDelayEndTimestamp + withdrawalTimeout >= block.timestamp, "Withdrawal timeout elapsed" ); uint256 covAmount = pendingWithdrawal[underwriter]; uint256 covSupply = underwriterToken.totalSupply(); delete withdrawalInitiatedTimestamp[underwriter]; delete pendingWithdrawal[underwriter]; // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 amountToWithdraw = (covAmount * collateralBalance) / covSupply; emit WithdrawalCompleted( underwriter, amountToWithdraw, covAmount, block.timestamp ); collateralToken.safeTransfer(underwriter, amountToWithdraw); /* solhint-enable not-rely-on-time */ underwriterToken.burn(covAmount); return amountToWithdraw; } /// @notice Transfers collateral tokens to a new Asset Pool which previously /// was approved by the governance. Upgrade does not have to obey /// withdrawal delay. /// Old underwriter tokens are burned in favor of new tokens minted /// in a new Asset Pool. New tokens are sent directly to the /// underwriter from a new Asset Pool. /// @param covAmount Amount of underwriter tokens used to calculate collateral /// tokens which are transferred to a new asset pool /// @param _newAssetPool New Asset Pool address to check validity with the one /// that was approved by the governance function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool) external { /* solhint-disable not-rely-on-time */ require( address(newAssetPool) != address(0), "New asset pool must be assigned" ); require( address(newAssetPool) == _newAssetPool, "Addresses of a new asset pool must match" ); require( covAmount > 0, "Underwriter token amount must be greater than 0" ); uint256 covSupply = underwriterToken.totalSupply(); // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 collateralToTransfer = (covAmount * collateralBalance) / covSupply; collateralToken.safeApprove( address(newAssetPool), collateralToTransfer ); // old underwriter tokens are burned in favor of new minted in a new // asset pool underwriterToken.burnFrom(msg.sender, covAmount); // collateralToTransfer will be sent to a new AssetPool and new // underwriter tokens will be minted and transferred back to the underwriter newAssetPool.depositFor(msg.sender, collateralToTransfer); emit AssetPoolUpgraded( msg.sender, collateralToTransfer, covAmount, block.timestamp ); } /// @notice Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { require( address(_newAssetPool) != address(0), "New asset pool can't be zero address" ); newAssetPool = _newAssetPool; emit ApprovedAssetPoolUpgrade(address(_newAssetPool)); } /// @notice Allows governance to cancel already approved new asset pool /// in case of some misconfiguration. function cancelNewAssetPoolUpgrade() external onlyOwner { emit CancelledAssetPoolUpgrade(address(newAssetPool)); newAssetPool = IAssetPoolUpgrade(address(0)); } /// @notice Allows the coverage pool to demand coverage from the asset hold /// by this pool and send it to the provided recipient address. function claim(address recipient, uint256 amount) external onlyOwner { emit CoverageClaimed(recipient, amount, block.timestamp); rewardsPool.withdraw(); collateralToken.safeTransfer(recipient, amount); } /// @notice Lets the contract owner to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param _newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 _newWithdrawalDelay) external onlyOwner { newWithdrawalDelay = _newWithdrawalDelay; withdrawalDelayChangeInitiated = block.timestamp; emit WithdrawalDelayUpdateStarted(_newWithdrawalDelay, block.timestamp); } /// @notice Lets the contract owner to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalDelayChangeInitiated) { withdrawalDelay = newWithdrawalDelay; emit WithdrawalDelayUpdated(withdrawalDelay); newWithdrawalDelay = 0; withdrawalDelayChangeInitiated = 0; } /// @notice Lets the contract owner to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param _newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 _newWithdrawalTimeout) external onlyOwner { newWithdrawalTimeout = _newWithdrawalTimeout; withdrawalTimeoutChangeInitiated = block.timestamp; emit WithdrawalTimeoutUpdateStarted( _newWithdrawalTimeout, block.timestamp ); } /// @notice Lets the contract owner to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalTimeoutChangeInitiated) { withdrawalTimeout = newWithdrawalTimeout; emit WithdrawalTimeoutUpdated(withdrawalTimeout); newWithdrawalTimeout = 0; withdrawalTimeoutChangeInitiated = 0; } /// @notice Grants pool shares by minting a given amount of the underwriter /// tokens for the recipient address. In result, the recipient /// obtains part of the pool ownership without depositing any /// collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by the contract owner. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantShares(address recipient, uint256 covAmount) external onlyOwner { rewardsPool.withdraw(); underwriterToken.mint(recipient, covAmount); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal delay update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal delay update can be finalized function getRemainingWithdrawalDelayUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalDelayChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal timeout update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal timeout update can be finalized function getRemainingWithdrawalTimeoutUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalTimeoutChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the current collateral token balance of the asset pool /// plus the reward amount (in collateral token) earned by the asset /// pool and not yet withdrawn to the asset pool. /// @return The total value of asset pool in collateral token. function totalValue() external view returns (uint256) { return collateralToken.balanceOf(address(this)) + rewardsPool.earned(); } /// @notice The time it takes to initiate and complete the withdrawal from /// the pool plus 2 days to make a decision. This governance delay /// should be used for all changes directly affecting underwriter /// positions. This time is a minimum and the governance may choose /// to wait longer before finalizing the update. /// @return The withdrawal governance delay in seconds function withdrawalGovernanceDelay() public view returns (uint256) { return withdrawalDelay + withdrawalTimeout + 2 days; } /// @dev Calculates underwriter tokens to mint. function _calculateTokensToMint(uint256 amountToDeposit) internal returns (uint256) { rewardsPool.withdraw(); uint256 covSupply = underwriterToken.totalSupply(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); if (covSupply == 0) { return amountToDeposit; } return (amountToDeposit * covSupply) / collateralBalance; } function _deposit( address depositor, uint256 amountToDeposit, uint256 amountToMint ) internal { require(depositor != address(this), "Self-deposit not allowed"); require( amountToMint > 0, "Minted tokens amount must be greater than 0" ); emit Deposited(depositor, amountToDeposit, amountToMint); underwriterToken.mint(depositor, amountToMint); collateralToken.safeTransferFrom( depositor, address(this), amountToDeposit ); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAuction.sol"; import "./Auctioneer.sol"; import "./CoveragePoolConstants.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title Auction /// @notice A contract to run a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral /// pool. Auctions can be partially filled, and are meant to be amenable /// to flash loans and other atomic constructions to take advantage of /// arbitrage opportunities within a single block. /// @dev Auction contracts are not meant to be deployed directly, and are /// instead cloned by an auction factory. Auction contracts clean up and /// self-destruct on close. An auction that has run the entire length will /// stay open, forever, or until priced fluctuate and it's eventually /// profitable to close. contract Auction is IAuction { using SafeERC20 for IERC20; struct AuctionStorage { IERC20 tokenAccepted; Auctioneer auctioneer; // the auction price, denominated in tokenAccepted uint256 amountOutstanding; uint256 amountDesired; uint256 startTime; uint256 startTimeOffset; uint256 auctionLength; } AuctionStorage public self; address public immutable masterContract; /// @notice Throws if called by any account other than the auctioneer. modifier onlyAuctioneer() { //slither-disable-next-line incorrect-equality require( msg.sender == address(self.auctioneer), "Caller is not the auctioneer" ); _; } constructor() { masterContract = address(this); } /// @notice Initializes auction /// @dev At the beginning of an auction, velocity pool depleting rate is /// always 1. It increases over time after a partial auction buy. /// @param _auctioneer the auctioneer contract responsible for seizing /// funds from the backing collateral pool /// @param _tokenAccepted the token with which the auction can be taken /// @param _amountDesired the amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param _auctionLength the amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function initialize( Auctioneer _auctioneer, IERC20 _tokenAccepted, uint256 _amountDesired, uint256 _auctionLength ) external { require(!isMasterContract(), "Can not initialize master contract"); //slither-disable-next-line incorrect-equality require(self.startTime == 0, "Auction already initialized"); require(_amountDesired > 0, "Amount desired must be greater than zero"); require(_auctionLength > 0, "Auction length must be greater than zero"); self.auctioneer = _auctioneer; self.tokenAccepted = _tokenAccepted; self.amountOutstanding = _amountDesired; self.amountDesired = _amountDesired; /* solhint-disable-next-line not-rely-on-time */ self.startTime = block.timestamp; self.startTimeOffset = 0; self.auctionLength = _auctionLength; } /// @notice Takes an offer from an auction buyer. /// @dev There are two possible ways to take an offer from a buyer. The first /// one is to buy entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// WARNING: When calling this function directly, it might happen that /// the expected amount of tokens to seize from the coverage pool is /// different from the actual one. There are a couple of reasons for that /// such another bids taking this offer, claims or withdrawals on an /// Asset Pool that are executed in the same block. The recommended way /// for taking an offer is through 'AuctionBidder' contract with /// 'takeOfferWithMin' function, where a caller can specify the minimal /// value to receive from the coverage pool in exchange for its amount /// of tokenAccepted. /// @param amount the amount the taker is paying, denominated in tokenAccepted. /// In the scenario when amount exceeds the outstanding tokens /// for the auction to complete, only the amount outstanding will /// be taken from a caller. function takeOffer(uint256 amount) external override { require(amount > 0, "Can't pay 0 tokens"); uint256 amountToTransfer = Math.min(amount, self.amountOutstanding); uint256 amountOnOffer = _onOffer(); //slither-disable-next-line reentrancy-no-eth self.tokenAccepted.safeTransferFrom( msg.sender, address(self.auctioneer), amountToTransfer ); uint256 portionToSeize = (amountOnOffer * amountToTransfer) / self.amountOutstanding; if (!isAuctionOver() && amountToTransfer != self.amountOutstanding) { // Time passed since the auction start or the last takeOffer call // with a partial fill. uint256 timePassed /* solhint-disable-next-line not-rely-on-time */ = block.timestamp - self.startTime - self.startTimeOffset; // Ratio of the auction's amount included in this takeOffer call to // the whole outstanding auction amount. uint256 ratioAmountPaid = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * amountToTransfer) / self.amountOutstanding; // We will shift the start time offset and increase the velocity pool // depleting rate proportionally to the fraction of the outstanding // amount paid in this function call so that the auction can offer // no worse financial outcome for the next takers than the current // taker has. // //slither-disable-next-line divide-before-multiply self.startTimeOffset = self.startTimeOffset + ((timePassed * ratioAmountPaid) / CoveragePoolConstants.FLOATING_POINT_DIVISOR); } self.amountOutstanding -= amountToTransfer; //slither-disable-next-line incorrect-equality bool isFullyFilled = self.amountOutstanding == 0; // inform auctioneer of proceeds and winner. the auctioneer seizes funds // from the collateral pool in the name of the winner, and controls all // proceeds // //slither-disable-next-line reentrancy-no-eth self.auctioneer.offerTaken( msg.sender, self.tokenAccepted, amountToTransfer, portionToSeize, isFullyFilled ); //slither-disable-next-line incorrect-equality if (isFullyFilled) { harikari(); } } /// @notice Tears down the auction manually, before its entire amount /// is bought by takers. /// @dev Can be called only by the auctioneer which may decide to early // close the auction in case it is no longer needed. function earlyClose() external onlyAuctioneer { require(self.amountOutstanding > 0, "Auction must be open"); harikari(); } /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @dev _onOffer() / FLOATING_POINT_DIVISOR) returns a portion of the /// collateral pool. Ex. if 35% available of the collateral pool, /// then _onOffer() / FLOATING_POINT_DIVISOR) returns 0.35 /// @return the ratio of the collateral pool currently on offer function onOffer() external view override returns (uint256, uint256) { return (_onOffer(), CoveragePoolConstants.FLOATING_POINT_DIVISOR); } function amountOutstanding() external view returns (uint256) { return self.amountOutstanding; } function amountTransferred() external view returns (uint256) { return self.amountDesired - self.amountOutstanding; } /// @dev Delete all storage and destroy the contract. Should only be called /// after an auction has closed. function harikari() internal { require(!isMasterContract(), "Master contract can not harikari"); selfdestruct(payable(address(self.auctioneer))); } function _onOffer() internal view returns (uint256) { // when the auction is over, entire pool is on offer if (isAuctionOver()) { // Down the road, for determining a portion on offer, a value returned // by this function will be divided by FLOATING_POINT_DIVISOR. To // return the entire pool, we need to return just this divisor in order // to get 1.0 ie. FLOATING_POINT_DIVISOR / FLOATING_POINT_DIVISOR = 1.0 return CoveragePoolConstants.FLOATING_POINT_DIVISOR; } // How fast portions of the collateral pool become available on offer. // It is needed to calculate the right portion value on offer at the // given moment before the auction is over. // Auction length once set is constant and what changes is the auction's // "start time offset" once the takeOffer() call has been processed for // partial fill. The auction's "start time offset" is updated every takeOffer(). // velocityPoolDepletingRate = auctionLength / (auctionLength - startTimeOffset) // velocityPoolDepletingRate always starts at 1.0 and then can go up // depending on partial offer calls over auction life span to maintain // the right ratio between the remaining auction time and the remaining // portion of the collateral pool. //slither-disable-next-line divide-before-multiply uint256 velocityPoolDepletingRate = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * self.auctionLength) / (self.auctionLength - self.startTimeOffset); return /* solhint-disable-next-line not-rely-on-time */ ((block.timestamp - (self.startTime + self.startTimeOffset)) * velocityPoolDepletingRate) / self.auctionLength; } function isAuctionOver() internal view returns (bool) { /* solhint-disable-next-line not-rely-on-time */ return block.timestamp >= self.startTime + self.auctionLength; } function isMasterContract() internal view returns (bool) { return masterContract == address(this); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./Auction.sol"; import "./CoveragePool.sol"; import "@thesis/solidity-contracts/contracts/clone/CloneFactory.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Auctioneer /// @notice Factory for the creation of new auction clones and receiving proceeds. /// @dev We avoid redeployment of auction contracts by using the clone factory. /// Proxy delegates calls to Auction and therefore does not affect auction state. /// This means that we only need to deploy the auction contracts once. /// The auctioneer provides clean state for every new auction clone. contract Auctioneer is CloneFactory { // Holds the address of the auction contract // which will be used as a master contract for cloning. address public immutable masterAuction; mapping(address => bool) public openAuctions; uint256 public openAuctionsCount; CoveragePool public immutable coveragePool; event AuctionCreated( address indexed tokenAccepted, uint256 amount, address auctionAddress ); event AuctionOfferTaken( address indexed auction, address indexed offerTaker, address tokenAccepted, uint256 amount, uint256 portionToSeize // This amount should be divided by FLOATING_POINT_DIVISOR ); event AuctionClosed(address indexed auction); constructor(CoveragePool _coveragePool, address _masterAuction) { coveragePool = _coveragePool; // slither-disable-next-line missing-zero-check masterAuction = _masterAuction; } /// @notice Informs the auctioneer to seize funds and log appropriate events /// @dev This function is meant to be called from a cloned auction. It logs /// "offer taken" and "auction closed" events, seizes funds, and cleans /// up closed auctions. /// @param offerTaker The address of the taker of the auction offer, /// who will receive the pool's seized funds /// @param tokenPaid The token this auction is denominated in /// @param tokenAmountPaid The amount of the token the taker paid /// @param portionToSeize The portion of the pool the taker won at auction. /// This amount should be divided by FLOATING_POINT_DIVISOR /// to calculate how much of the pool should be set /// aside as the taker's winnings. /// @param fullyFilled Indicates whether the auction was taken fully or /// partially. If auction was fully filled, it is /// closed. If auction was partially filled, it is /// sill open and waiting for remaining bids. function offerTaken( address offerTaker, IERC20 tokenPaid, uint256 tokenAmountPaid, uint256 portionToSeize, bool fullyFilled ) external { require(openAuctions[msg.sender], "Sender isn't an auction"); emit AuctionOfferTaken( msg.sender, offerTaker, address(tokenPaid), tokenAmountPaid, portionToSeize ); // actually seize funds, setting them aside for the taker to withdraw // from the coverage pool. // `portionToSeize` will be divided by FLOATING_POINT_DIVISOR which is // defined in Auction.sol // //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign coveragePool.seizeFunds(offerTaker, portionToSeize); Auction auction = Auction(msg.sender); if (fullyFilled) { onAuctionFullyFilled(auction); emit AuctionClosed(msg.sender); delete openAuctions[msg.sender]; openAuctionsCount -= 1; } else { onAuctionPartiallyFilled(auction); } } /// @notice Opens a new auction against the coverage pool. The auction /// will remain open until filled. /// @dev Calls `Auction.initialize` to initialize the instance. /// @param tokenAccepted The token with which the auction can be taken /// @param amountDesired The amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param auctionLength The amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function createAuction( IERC20 tokenAccepted, uint256 amountDesired, uint256 auctionLength ) internal returns (address) { address cloneAddress = createClone(masterAuction); require(cloneAddress != address(0), "Cloned auction address is 0"); Auction auction = Auction(cloneAddress); //slither-disable-next-line reentrancy-benign,reentrancy-events auction.initialize(this, tokenAccepted, amountDesired, auctionLength); openAuctions[cloneAddress] = true; openAuctionsCount += 1; emit AuctionCreated( address(tokenAccepted), amountDesired, cloneAddress ); return cloneAddress; } /// @notice Tears down an open auction with given address immediately. /// @dev Can be called by contract owner to early close an auction if it /// is no longer needed. Bear in mind that funds from the early closed /// auction last on the auctioneer contract. Calling code should take /// care of them. /// @return Amount of funds transferred to this contract by the Auction /// being early closed. function earlyCloseAuction(Auction auction) internal returns (uint256) { address auctionAddress = address(auction); require(openAuctions[auctionAddress], "Address is not an open auction"); uint256 amountTransferred = auction.amountTransferred(); //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign auction.earlyClose(); emit AuctionClosed(auctionAddress); delete openAuctions[auctionAddress]; openAuctionsCount -= 1; return amountTransferred; } /// @notice Auction lifecycle hook allowing to act on auction closed /// as fully filled. This function is not executed when an auction /// was partially filled. When this function is executed auction is /// already closed and funds from the coverage pool are seized. /// @dev Override this function to act on auction closed as fully filled. function onAuctionFullyFilled(Auction auction) internal virtual {} /// @notice Auction lifecycle hook allowing to act on auction partially /// filled. This function is not executed when an auction /// was fully filled. /// @dev Override this function to act on auction partially filled. function onAuctionPartiallyFilled(Auction auction) internal view virtual {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPoolUpgrade.sol"; import "./AssetPool.sol"; import "./CoveragePoolConstants.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Coverage Pool /// @notice A contract that manages a single asset pool. Handles approving and /// unapproving of risk managers and allows them to seize funds from the /// asset pool if they are approved. /// @dev Coverage pool contract is owned by the governance. Coverage pool is the /// owner of the asset pool contract. contract CoveragePool is Ownable { AssetPool public immutable assetPool; IERC20 public immutable collateralToken; bool public firstRiskManagerApproved = false; // Currently approved risk managers mapping(address => bool) public approvedRiskManagers; // Timestamps of risk managers whose approvals have been initiated mapping(address => uint256) public riskManagerApprovalTimestamps; event RiskManagerApprovalStarted(address riskManager, uint256 timestamp); event RiskManagerApprovalCompleted(address riskManager, uint256 timestamp); event RiskManagerUnapproved(address riskManager, uint256 timestamp); /// @notice Reverts if called by a risk manager that is not approved modifier onlyApprovedRiskManager() { require(approvedRiskManagers[msg.sender], "Risk manager not approved"); _; } constructor(AssetPool _assetPool) { assetPool = _assetPool; collateralToken = _assetPool.collateralToken(); } /// @notice Approves the first risk manager /// @dev Can be called only by the contract owner. Can be called only once. /// Does not require any further calls to any functions. /// @param riskManager Risk manager that will be approved function approveFirstRiskManager(address riskManager) external onlyOwner { require( !firstRiskManagerApproved, "The first risk manager was approved" ); approvedRiskManagers[riskManager] = true; firstRiskManagerApproved = true; } /// @notice Begins risk manager approval process. /// @dev Can be called only by the contract owner and only when the first /// risk manager is already approved. For a risk manager to be /// approved, a call to `finalizeRiskManagerApproval` must follow /// (after a governance delay). /// @param riskManager Risk manager that will be approved function beginRiskManagerApproval(address riskManager) external onlyOwner { require( firstRiskManagerApproved, "The first risk manager is not yet approved; Please use " "approveFirstRiskManager instead" ); require( !approvedRiskManagers[riskManager], "Risk manager already approved" ); /* solhint-disable-next-line not-rely-on-time */ riskManagerApprovalTimestamps[riskManager] = block.timestamp; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalStarted(riskManager, block.timestamp); } /// @notice Finalizes risk manager approval process. /// @dev Can be called only by the contract owner. Must be preceded with a /// call to beginRiskManagerApproval and a governance delay must elapse. /// @param riskManager Risk manager that will be approved function finalizeRiskManagerApproval(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0, "Risk manager approval not initiated" ); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - riskManagerApprovalTimestamps[riskManager] >= assetPool.withdrawalGovernanceDelay(), "Risk manager governance delay has not elapsed" ); approvedRiskManagers[riskManager] = true; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalCompleted(riskManager, block.timestamp); delete riskManagerApprovalTimestamps[riskManager]; } /// @notice Unapproves an already approved risk manager or cancels the /// approval process of a risk manager (the latter happens if called /// between `beginRiskManagerApproval` and `finalizeRiskManagerApproval`). /// The change takes effect immediately. /// @dev Can be called only by the contract owner. /// @param riskManager Risk manager that will be unapproved function unapproveRiskManager(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0 || approvedRiskManagers[riskManager], "Risk manager is neither approved nor with a pending approval" ); delete riskManagerApprovalTimestamps[riskManager]; delete approvedRiskManagers[riskManager]; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerUnapproved(riskManager, block.timestamp); } /// @notice Approves upgradeability to the new asset pool. /// Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. /// @param _newAssetPool New asset pool function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { assetPool.approveNewAssetPoolUpgrade(_newAssetPool); } /// @notice Lets the governance to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 newWithdrawalDelay) external onlyOwner { assetPool.beginWithdrawalDelayUpdate(newWithdrawalDelay); } /// @notice Lets the governance to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner { assetPool.finalizeWithdrawalDelayUpdate(); } /// @notice Lets the governance to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 newWithdrawalTimeout) external onlyOwner { assetPool.beginWithdrawalTimeoutUpdate(newWithdrawalTimeout); } /// @notice Lets the governance to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner { assetPool.finalizeWithdrawalTimeoutUpdate(); } /// @notice Seizes funds from the coverage pool and puts them aside for the /// recipient to withdraw. /// @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR` /// for calculation precision purposes. Further calculations in this /// function will need to take this divisor into account. /// @param recipient Address that will receive the pool's seized funds /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by `FLOATING_POINT_DIVISOR` function seizeFunds(address recipient, uint256 portionToSeize) external onlyApprovedRiskManager { require( portionToSeize > 0 && portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR, "Portion to seize is not within the range (0, 1]" ); assetPool.claim(recipient, amountToSeize(portionToSeize)); } /// @notice Grants asset pool shares by minting a given amount of the /// underwriter tokens for the recipient address. In result, the /// recipient obtains part of the pool ownership without depositing /// any collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by an approved risk manager. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantAssetPoolShares(address recipient, uint256 covAmount) external onlyApprovedRiskManager { assetPool.grantShares(recipient, covAmount); } /// @notice Returns the time remaining until the risk manager approval /// process can be finalized /// @param riskManager Risk manager in the process of approval /// @return Remaining time in seconds. function getRemainingRiskManagerApprovalTime(address riskManager) external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( riskManagerApprovalTimestamps[riskManager], assetPool.withdrawalGovernanceDelay() ); } /// @notice Calculates amount of tokens to be seized from the coverage pool. /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by FLOATING_POINT_DIVISOR function amountToSeize(uint256 portionToSeize) public view returns (uint256) { return (collateralToken.balanceOf(address(assetPool)) * portionToSeize) / CoveragePoolConstants.FLOATING_POINT_DIVISOR; } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library CoveragePoolConstants { // This divisor is for precision purposes only. We use this divisor around // auction related code to get the precise values without rounding it down // when dealing with floating numbers. uint256 public constant FLOATING_POINT_DIVISOR = 1e18; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library GovernanceUtils { /// @notice Gets the time remaining until the governable parameter update /// can be committed. /// @param changeTimestamp Timestamp indicating the beginning of the change. /// @param delay Governance delay. /// @return Remaining time in seconds. function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay) internal view returns (uint256) { require(changeTimestamp > 0, "Change not initiated"); /* solhint-disable-next-line not-rely-on-time */ uint256 elapsed = block.timestamp - changeTimestamp; if (elapsed >= delay) { return 0; } else { return delay - elapsed; } } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Rewards Pool /// @notice RewardsPool accepts a single reward token and releases it to the /// AssetPool over time in one week reward intervals. The owner of this /// contract is the reward distribution address funding it with reward /// tokens. contract RewardsPool is Ownable { using SafeERC20 for IERC20; uint256 public constant DURATION = 7 days; IERC20 public immutable rewardToken; address public immutable assetPool; // timestamp of the current reward interval end or the timestamp of the // last interval end in case a new reward interval has not been allocated uint256 public intervalFinish = 0; // rate per second with which reward tokens are unlocked uint256 public rewardRate = 0; // amount of rewards accumulated and not yet withdrawn from the previous // reward interval(s) uint256 public rewardAccumulated = 0; // the last time information in this contract was updated uint256 public lastUpdateTime = 0; event RewardToppedUp(uint256 amount); event RewardWithdrawn(uint256 amount); constructor( IERC20 _rewardToken, address _assetPool, address owner ) { rewardToken = _rewardToken; // slither-disable-next-line missing-zero-check assetPool = _assetPool; transferOwnership(owner); } /// @notice Transfers the provided reward amount into RewardsPool and /// creates a new, one-week reward interval starting from now. /// Reward tokens from the previous reward interval that unlocked /// over the time will be available for withdrawal immediately. /// Reward tokens from the previous interval that has not been yet /// unlocked, are added to the new interval being created. /// @dev This function can be called only by the owner given that it creates /// a new interval with one week length, starting from now. function topUpReward(uint256 reward) external onlyOwner { rewardAccumulated = earned(); /* solhint-disable not-rely-on-time */ if (block.timestamp >= intervalFinish) { // see https://github.com/crytic/slither/issues/844 // slither-disable-next-line divide-before-multiply rewardRate = reward / DURATION; } else { uint256 remaining = intervalFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / DURATION; } intervalFinish = block.timestamp + DURATION; lastUpdateTime = block.timestamp; /* solhint-enable avoid-low-level-calls */ emit RewardToppedUp(reward); rewardToken.safeTransferFrom(msg.sender, address(this), reward); } /// @notice Withdraws all unlocked reward tokens to the AssetPool. function withdraw() external { uint256 amount = earned(); rewardAccumulated = 0; lastUpdateTime = lastTimeRewardApplicable(); emit RewardWithdrawn(amount); rewardToken.safeTransfer(assetPool, amount); } /// @notice Returns the amount of earned and not yet withdrawn reward /// tokens. function earned() public view returns (uint256) { return rewardAccumulated + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate); } /// @notice Returns the timestamp at which a reward was last time applicable. /// When reward interval is pending, returns current block's /// timestamp. If the last reward interval ended and no other reward /// interval had been allocated, returns the last reward interval's /// end timestamp. function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, intervalFinish); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol"; /// @title UnderwriterToken /// @notice Underwriter tokens represent an ownership share in the underlying /// collateral of the asset-specific pool. Underwriter tokens are minted /// when a user deposits ERC20 tokens into asset-specific pool and they /// are burned when a user exits the position. Underwriter tokens /// natively support meta transactions. Users can authorize a transfer /// of their underwriter tokens with a signature conforming EIP712 /// standard instead of an on-chain transaction from their address. /// Anyone can submit this signature on the user's behalf by calling the /// permit function, as specified in EIP2612 standard, paying gas fees, /// and possibly performing other actions in the same transaction. contract UnderwriterToken is ERC20WithPermit { constructor(string memory _name, string memory _symbol) ERC20WithPermit(_name, _symbol) {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool interface /// @notice Asset Pool accepts a single ERC20 token as collateral, and returns /// an underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. interface IAssetPool { /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function deposit(uint256 amount) external returns (uint256); /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external returns (uint256); /// @notice Initiates the withdrawal of collateral and rewards from the pool. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external; /// @notice Completes the previously initiated withdrawal for the /// underwriter. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external returns (uint256); } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool upgrade interface /// @notice Interface that has to be implemented by an Asset Pool accepting /// upgrades from another asset pool. interface IAssetPoolUpgrade { /// @notice Accepts the given underwriter with collateral tokens amount as a /// deposit. In exchange new underwriter tokens will be calculated, /// minted and then transferred back to the underwriter. function depositFor(address underwriter, uint256 amount) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Auction interface /// @notice Auction runs a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral interface IAuction { /// @notice Takes an offer from an auction buyer. There are two possible /// ways to take an offer from a buyer. The first one is to buy /// entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// @dev The implementation is not guaranteed to be protecting against /// frontrunning. See `AuctionBidder` for an example protection. function takeOffer(uint256 amount) external; /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @return The ratio of the collateral pool currently on offer and divisor /// for precision purposes. function onOffer() external view returns (uint256, uint256); }
@notice Creates EIP-1167 clone of the contract under the provided `target` address. Returns address of the created clone. @dev In specific circumstances, such as the `target` contract destroyed, create opcode may return 0x0 address. The code calling this function should handle this corner case properly.
function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } }
112,325
[ 1, 2729, 512, 2579, 17, 20562, 27, 3236, 434, 326, 6835, 3613, 326, 2112, 540, 1375, 3299, 68, 1758, 18, 2860, 1758, 434, 326, 2522, 3236, 18, 225, 657, 2923, 29951, 2639, 16, 4123, 487, 326, 1375, 3299, 68, 6835, 17689, 16, 1377, 752, 11396, 2026, 327, 374, 92, 20, 1758, 18, 1021, 981, 4440, 333, 1377, 445, 1410, 1640, 333, 11055, 648, 8214, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 752, 10930, 12, 2867, 1018, 13, 2713, 1135, 261, 2867, 563, 13, 288, 203, 3639, 1731, 3462, 1018, 2160, 273, 1731, 3462, 12, 3299, 1769, 203, 3639, 19931, 288, 203, 5411, 2231, 3236, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 5411, 312, 2233, 12, 203, 7734, 3236, 16, 203, 7734, 374, 92, 23, 72, 26, 3103, 72, 3672, 28133, 69, 23, 72, 5520, 11861, 74, 3707, 4449, 72, 23, 72, 6418, 23, 72, 23, 72, 23, 72, 23, 4449, 72, 9036, 12648, 12648, 12648, 203, 5411, 262, 203, 5411, 312, 2233, 12, 1289, 12, 14056, 16, 374, 92, 3461, 3631, 1018, 2160, 13, 203, 5411, 312, 2233, 12, 203, 7734, 527, 12, 14056, 16, 374, 92, 6030, 3631, 203, 7734, 374, 92, 25, 1727, 8942, 72, 11149, 3672, 23, 73, 29, 4630, 72, 29, 2313, 3103, 70, 10321, 8313, 25, 17156, 23, 12648, 12648, 12648, 2787, 9449, 203, 5411, 262, 203, 5411, 563, 519, 752, 12, 20, 16, 3236, 16, 374, 92, 6418, 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 ]
// IKB TOKEN // By Mitchell F. Chan /* OVERVIEW: This contract manages the purchase and transferral of Digital Zones of Immaterial Pictorial Sensibility. It reproduces the rules originally created by Yves Klein which governed the transferral of his original Zones of Immaterial Pictorial Sensibility. The project is described in full in the Blue Paper included in this repository. */ pragma solidity ^0.4.15; // interface for ERC20 standard token contract ERC20 { function totalSupply() constant returns (uint256 currentSupply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // token boilerplate contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } // library for math to prevent underflows and overflows contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0) || (z / x == y)); return z; } } contract Klein is ERC20, owned, SafeMath { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; mapping (address => mapping (address => mapping (uint256 => bool))) specificAllowed; // The Swarm address of the artwork is saved here for reference and posterity string public constant zonesSwarmAddress = "0a52f265d8d60a89de41a65069fa472ac3b130c269b4788811220b6546784920"; address public constant theRiver = 0x8aDE9bCdA847852DE70badA69BBc9358C1c7B747; // ROPSTEN REVIVAL address string public constant name = "Digital Zone of Immaterial Pictorial Sensibility"; string public constant symbol = "IKB"; uint256 public constant decimals = 0; uint256 public maxSupplyPossible; uint256 public initialPrice = 10**17; // should equal 0.1 ETH uint256 public currentSeries; uint256 public issuedToDate; uint256 public totalSold; uint256 public burnedToDate; bool first = true; // IKB are issued in tranches, or series of editions. There will be 8 total // Each IBKSeries represents one of Klein's receipt books, or a series of issued tokens. struct IKBSeries { uint256 price; uint256 seriesSupply; } IKBSeries[8] public series; // An array of all 8 series struct record { address addr; uint256 price; bool burned; } record[101] public records; // An array of all 101 records event UpdateRecord(uint indexed IKBedition, address holderAddress, uint256 price, bool burned); event SeriesCreated(uint indexed seriesNum); event SpecificApproval(address indexed owner, address indexed spender, uint256 indexed edition); function Klein() { currentSeries = 0; series[0] = IKBSeries(initialPrice, 31); // the first series has unique values... for(uint256 i = 1; i < series.length; i++){ // ...while the next 7 can be defined in a for loop series[i] = IKBSeries(series[i-1].price*2, 10); } maxSupplyPossible = 101; } function() payable { buy(); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function specificApprove(address _spender, uint256 _edition) returns (bool success) { specificAllowed[msg.sender][_spender][_edition] = true; SpecificApproval(msg.sender, _spender, _edition); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // NEW: I thought it was more in keeping with what totalSupply() is supposed to be about to return how many tokens are currently in circulation function totalSupply() constant returns (uint _currentSupply) { return (issuedToDate - burnedToDate); } function issueNewSeries() onlyOwner returns (bool success){ require(balances[this] <= 0); //can only issue a new series if you've sold all the old ones require(currentSeries < 7); if(!first){ currentSeries++; // the first time we run this function, don't run up the currentSeries counter. Keep it at 0 } else if (first){ first=false; // ...but only let this work once. } balances[this] = safeAdd(balances[this], series[currentSeries].seriesSupply); issuedToDate = safeAdd(issuedToDate, series[currentSeries].seriesSupply); SeriesCreated(currentSeries); return true; } function buy() payable returns (bool success){ require(balances[this] > 0); require(msg.value >= series[currentSeries].price); uint256 amount = msg.value / series[currentSeries].price; // calculates the number of tokens the sender will buy uint256 receivable = msg.value; if (balances[this] < amount) { // this section handles what happens if someone tries to buy more than the currently available supply receivable = safeMult(balances[this], series[currentSeries].price); uint256 returnable = safeSubtract(msg.value, receivable); amount = balances[this]; msg.sender.transfer(returnable); } if (receivable % series[currentSeries].price > 0) assert(returnChange(receivable)); balances[msg.sender] = safeAdd(balances[msg.sender], amount); // adds the amount to buyer's balance balances[this] = safeSubtract(balances[this], amount); // subtracts amount from seller's balance Transfer(this, msg.sender, amount); // execute an event reflecting the change for(uint k = 0; k < amount; k++){ // now let's make a record of every sale records[totalSold] = record(msg.sender, series[currentSeries].price, false); totalSold++; } return true; // ends function and returns } function returnChange(uint256 _receivable) internal returns (bool success){ uint256 change = _receivable % series[currentSeries].price; msg.sender.transfer(change); return true; } // when this function is called, the caller is transferring any number of tokens. The function automatically chooses the tokens with the LOWEST index to transfer. function transfer(address _to, uint _value) returns (bool success) { require(balances[msg.sender] >= _value); require(_value > 0); uint256 recordsChanged = 0; for(uint k = 0; k < records.length; k++){ // go through every record if(records[k].addr == msg.sender && recordsChanged < _value) { records[k].addr = _to; // change the address associated with this record recordsChanged++; // keep track of how many records you've changed in this transfer. After you've changed as many records as there are tokens being transferred, conditions of this loop will cease to be true. UpdateRecord(k, _to, records[k].price, records[k].burned); } } balances[msg.sender] = safeSubtract(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(_value > 0); uint256 recordsChanged = 0; for(uint256 k = 0; k < records.length; k++){ // go through every record if(records[k].addr == _from && recordsChanged < _value) { records[k].addr = _to; // change the address associated with this record recordsChanged++; // keep track of how many records you've changed in this transfer. After you've changed as many records as there are tokens being transferred, conditions of this loop will cease to be true. UpdateRecord(k, _to, records[k].price, records[k].burned); } } balances[_from] = safeSubtract(balances[_from], _value); allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } // when this function is called, the caller is transferring only 1 IKB to another account, and specifying exactly which token they would like to transfer. function specificTransfer(address _to, uint _edition) returns (bool success) { require(balances[msg.sender] > 0); require(records[_edition].addr == msg.sender); balances[msg.sender] = safeSubtract(balances[msg.sender], 1); balances[_to] = safeAdd(balances[_to], 1); records[_edition].addr = _to; // update the records so that the record shows this person owns the Transfer(msg.sender, _to, 1); UpdateRecord(_edition, _to, records[_edition].price, records[_edition].burned); return true; } function specificTransferFrom(address _from, address _to, uint _edition) returns (bool success){ require(balances[_from] > 0); require(records[_edition].addr == _from); require(specificAllowed[_from][msg.sender][_edition]); balances[_from] = safeSubtract(balances[_from], 1); balances[_to] = safeAdd(balances[_to], 1); specificAllowed[_from][msg.sender][_edition] = false; records[_edition].addr = _to; // update the records so that the record shows this person owns the Transfer(msg.sender, _to, 1); UpdateRecord(_edition, _to, records[_edition].price, records[_edition].burned); return true; } // a quick way to figure out who holds a specific token without querying the whole record. This might actually be redundant. function getTokenHolder(uint searchedRecord) public constant returns(address){ return records[searchedRecord].addr; } function getHolderEditions(address _holder) public constant returns (uint256[] _editions) { uint256[] memory editionsOwned = new uint256[](balances[_holder]); uint256 index; for(uint256 k = 0; k < records.length; k++) { if(records[k].addr == _holder) { editionsOwned[index] = k; index++; } } return editionsOwned; } // allows the artist to withdraw ether from the contract function redeemEther() onlyOwner returns (bool success) { owner.transfer(this.balance); return true; } // allows the artist to put ether back in the contract so that holders can execute the ritual function function fund() payable onlyOwner returns (bool success) { return true; } function ritual(uint256 _edition) returns (bool success){ require(records[_edition].addr == msg.sender); require(!records[_edition].burned); uint256 halfTheGold = records[_edition].price / 2; require(this.balance >= halfTheGold); records[_edition].addr = 0xdead; records[_edition].burned = true; burnedToDate++; balances[msg.sender] = safeSubtract(balances[msg.sender], 1); theRiver.transfer(halfTheGold); // call should fail if this contract isn't holding enough ETH return true; } }
execute an event reflecting the change
Transfer(this, msg.sender, amount);
12,666,868
[ 1, 8837, 392, 871, 3037, 310, 326, 2549, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12279, 12, 2211, 16, 1234, 18, 15330, 16, 3844, 1769, 12900, 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.6.6; pragma experimental ABIEncoderV2; import './Ownable.sol'; import './SafeMath.sol'; import './Address.sol'; import './ACONameFormatter.sol'; import './ACOAssetHelper.sol'; import './ERC20.sol'; import './IACOPool.sol'; import './IACOFactory.sol'; import './IACOStrategy.sol'; import './IACOToken.sol'; import './IACOFlashExercise.sol'; import './IUniswapV2Router02.sol'; import './IChiToken.sol'; /** * @title ACOPool * @dev A pool contract to trade ACO tokens. */ contract ACOPool is Ownable, ERC20, IACOPool { using Address for address; using SafeMath for uint256; uint256 internal constant POOL_PRECISION = 1000000000000000000; // 18 decimals uint256 internal constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Struct to store an ACO token trade data. */ struct ACOTokenData { /** * @dev Amount of tokens sold by the pool. */ uint256 amountSold; /** * @dev Amount of tokens purchased by the pool. */ uint256 amountPurchased; /** * @dev Index of the ACO token on the stored array. */ uint256 index; } /** * @dev Emitted when the strategy address has been changed. * @param oldStrategy Address of the previous strategy. * @param newStrategy Address of the new strategy. */ event SetStrategy(address indexed oldStrategy, address indexed newStrategy); /** * @dev Emitted when the base volatility has been changed. * @param oldBaseVolatility Value of the previous base volatility. * @param newBaseVolatility Value of the new base volatility. */ event SetBaseVolatility(uint256 indexed oldBaseVolatility, uint256 indexed newBaseVolatility); /** * @dev Emitted when a collateral has been deposited on the pool. * @param account Address of the account. * @param amount Amount deposited. */ event CollateralDeposited(address indexed account, uint256 amount); /** * @dev Emitted when the collateral and premium have been redeemed on the pool. * @param account Address of the account. * @param underlyingAmount Amount of underlying asset redeemed. * @param strikeAssetAmount Amount of strike asset redeemed. */ event Redeem(address indexed account, uint256 underlyingAmount, uint256 strikeAssetAmount); /** * @dev Emitted when the collateral has been restored on the pool. * @param amountOut Amount of the premium sold. * @param collateralIn Amount of collateral restored. */ event RestoreCollateral(uint256 amountOut, uint256 collateralIn); /** * @dev Emitted when an ACO token has been redeemed. * @param acoToken Address of the ACO token. * @param collateralIn Amount of collateral redeemed. * @param amountSold Total amount of ACO token sold by the pool. * @param amountPurchased Total amount of ACO token purchased by the pool. */ event ACORedeem(address indexed acoToken, uint256 collateralIn, uint256 amountSold, uint256 amountPurchased); /** * @dev Emitted when an ACO token has been exercised. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens exercised. * @param collateralIn Amount of collateral received. */ event ACOExercise(address indexed acoToken, uint256 tokenAmount, uint256 collateralIn); /** * @dev Emitted when an ACO token has been bought or sold by the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param account Address of the account that is doing the swap. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens swapped. * @param price Value of the premium paid in strike asset. * @param protocolFee Value of the protocol fee paid in strike asset. * @param underlyingPrice The underlying price in strike asset. */ event Swap( bool indexed isPoolSelling, address indexed account, address indexed acoToken, uint256 tokenAmount, uint256 price, uint256 protocolFee, uint256 underlyingPrice ); /** * @dev UNIX timestamp that the pool can start to trade ACO tokens. */ uint256 public poolStart; /** * @dev The protocol fee percentage. (100000 = 100%) */ uint256 public fee; /** * @dev Address of the ACO flash exercise contract. */ IACOFlashExercise public acoFlashExercise; /** * @dev Address of the ACO factory contract. */ IACOFactory public acoFactory; /** * @dev Address of the Uniswap V2 router. */ IUniswapV2Router02 public uniswapRouter; /** * @dev Address of the Chi gas token. */ IChiToken public chiToken; /** * @dev Address of the protocol fee destination. */ address public feeDestination; /** * @dev Address of the underlying asset accepts by the pool. */ address public underlying; /** * @dev Address of the strike asset accepts by the pool. */ address public strikeAsset; /** * @dev Value of the minimum strike price on ACO token that the pool accept to trade. */ uint256 public minStrikePrice; /** * @dev Value of the maximum strike price on ACO token that the pool accept to trade. */ uint256 public maxStrikePrice; /** * @dev Value of the minimum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public minExpiration; /** * @dev Value of the maximum UNIX expiration on ACO token that the pool accept to trade. */ uint256 public maxExpiration; /** * @dev True whether the pool accepts CALL options, otherwise the pool accepts only PUT options. */ bool public isCall; /** * @dev True whether the pool can also buy ACO tokens, otherwise the pool only sells ACO tokens. */ bool public canBuy; /** * @dev Address of the strategy. */ IACOStrategy public strategy; /** * @dev Percentage value for the base volatility. (100000 = 100%) */ uint256 public baseVolatility; /** * @dev Total amount of collateral deposited. */ uint256 public collateralDeposited; /** * @dev Total amount in strike asset spent buying ACO tokens. */ uint256 public strikeAssetSpentBuying; /** * @dev Total amount in strike asset earned selling ACO tokens. */ uint256 public strikeAssetEarnedSelling; /** * @dev Array of ACO tokens currently negotiated. */ address[] public acoTokens; /** * @dev Mapping for ACO tokens data currently negotiated. */ mapping(address => ACOTokenData) public acoTokensData; /** * @dev Underlying asset precision. (18 decimals = 1000000000000000000) */ uint256 internal underlyingPrecision; /** * @dev Strike asset precision. (6 decimals = 1000000) */ uint256 internal strikeAssetPrecision; /** * @dev Modifier to check if the pool is open to trade. */ modifier open() { require(isStarted() && notFinished(), "ACOPool:: Pool is not open"); _; } /** * @dev Modifier to apply the Chi gas token and save gas. */ modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chiToken.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41947); } /** * @dev Function to initialize the contract. * It should be called by the ACO pool factory when creating the pool. * It must be called only once. The first `require` is to guarantee that behavior. * @param initData The initialize data. */ function init(InitData calldata initData) external override { require(underlying == address(0) && strikeAsset == address(0) && minExpiration == 0, "ACOPool::init: Already initialized"); require(initData.acoFactory.isContract(), "ACOPool:: Invalid ACO Factory"); require(initData.acoFlashExercise.isContract(), "ACOPool:: Invalid ACO flash exercise"); require(initData.chiToken.isContract(), "ACOPool:: Invalid Chi Token"); require(initData.fee <= 12500, "ACOPool:: The maximum fee allowed is 12.5%"); require(initData.poolStart > block.timestamp, "ACOPool:: Invalid pool start"); require(initData.minExpiration > block.timestamp, "ACOPool:: Invalid expiration"); require(initData.minStrikePrice <= initData.maxStrikePrice, "ACOPool:: Invalid strike price range"); require(initData.minStrikePrice > 0, "ACOPool:: Invalid strike price"); require(initData.minExpiration <= initData.maxExpiration, "ACOPool:: Invalid expiration range"); require(initData.underlying != initData.strikeAsset, "ACOPool:: Same assets"); require(ACOAssetHelper._isEther(initData.underlying) || initData.underlying.isContract(), "ACOPool:: Invalid underlying"); require(ACOAssetHelper._isEther(initData.strikeAsset) || initData.strikeAsset.isContract(), "ACOPool:: Invalid strike asset"); super.init(); poolStart = initData.poolStart; acoFlashExercise = IACOFlashExercise(initData.acoFlashExercise); acoFactory = IACOFactory(initData.acoFactory); chiToken = IChiToken(initData.chiToken); fee = initData.fee; feeDestination = initData.feeDestination; underlying = initData.underlying; strikeAsset = initData.strikeAsset; minStrikePrice = initData.minStrikePrice; maxStrikePrice = initData.maxStrikePrice; minExpiration = initData.minExpiration; maxExpiration = initData.maxExpiration; isCall = initData.isCall; canBuy = initData.canBuy; address _uniswapRouter = IACOFlashExercise(initData.acoFlashExercise).uniswapRouter(); uniswapRouter = IUniswapV2Router02(_uniswapRouter); _setStrategy(initData.strategy); _setBaseVolatility(initData.baseVolatility); _setAssetsPrecision(initData.underlying, initData.strikeAsset); _approveAssetsOnRouter(initData.isCall, initData.canBuy, _uniswapRouter, initData.underlying, initData.strikeAsset); } receive() external payable { } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals. */ function decimals() public view override returns(uint8) { return 18; } /** * @dev Function to get whether the pool already started trade ACO tokens. */ function isStarted() public view returns(bool) { return block.timestamp >= poolStart; } /** * @dev Function to get whether the pool is not finished. */ function notFinished() public view returns(bool) { return block.timestamp < maxExpiration; } /** * @dev Function to get the number of ACO tokens currently negotiated. */ function numberOfACOTokensCurrentlyNegotiated() public override view returns(uint256) { return acoTokens.length; } /** * @dev Function to get the pool collateral asset. */ function collateral() public override view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to quote an ACO token swap. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The swap price, the protocol fee charged on the swap, and the underlying price in strike asset. */ function quote(bool isBuying, address acoToken, uint256 tokenAmount) open public override view returns(uint256, uint256, uint256) { (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice,) = _internalQuote(isBuying, acoToken, tokenAmount); return (swapPrice, protocolFee, underlyingPrice); } /** * @dev Function to set the pool strategy address. * Only can be called by the ACO pool factory contract. * @param newStrategy Address of the new strategy. */ function setStrategy(address newStrategy) onlyOwner external override { _setStrategy(newStrategy); } /** * @dev Function to set the pool base volatility percentage. (100000 = 100%) * Only can be called by the ACO pool factory contract. * @param newBaseVolatility Value of the new base volatility. */ function setBaseVolatility(uint256 newBaseVolatility) onlyOwner external override { _setBaseVolatility(newBaseVolatility); } /** * @dev Function to deposit on the pool. * Only can be called when the pool is not started. * @param collateralAmount Amount of collateral to be deposited. * @param to Address of the destination of the pool token. * @return The amount of pool tokens minted. */ function deposit(uint256 collateralAmount, address to) public override payable returns(uint256) { require(!isStarted(), "ACOPool:: Pool already started"); require(collateralAmount > 0, "ACOPool:: Invalid collateral amount"); require(to != address(0) && to != address(this), "ACOPool:: Invalid to"); (uint256 normalizedAmount, uint256 amount) = _getNormalizedDepositAmount(collateralAmount); ACOAssetHelper._receiveAsset(collateral(), amount); collateralDeposited = collateralDeposited.add(amount); _mintAction(to, normalizedAmount); emit CollateralDeposited(msg.sender, amount); return normalizedAmount; } /** * @dev Function to swap an ACO token with the pool. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swap( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to swap an ACO token with the pool and use Chi token to save gas. * Only can be called when the pool is opened. * @param isBuying True whether it is quoting to buy an ACO token, otherwise it is quoting to sell an ACO token. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function swapWithGasToken( bool isBuying, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) open discountCHI public override returns(uint256) { return _swap(isBuying, acoToken, tokenAmount, restriction, to, deadline); } /** * @dev Function to redeem the collateral and the premium from the pool. * Only can be called when the pool is finished. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeem() public override returns(uint256, uint256) { return _redeem(msg.sender); } /** * @dev Function to redeem the collateral and the premium from the pool from an account. * Only can be called when the pool is finished. * The allowance must be respected. * The transaction sender will receive the redeemed assets. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function redeemFrom(address account) public override returns(uint256, uint256) { return _redeem(account); } /** * @dev Function to redeem the collateral from the ACO tokens negotiated on the pool. * It redeems the collateral only if the respective ACO token is expired. */ function redeemACOTokens() public override { for (uint256 i = acoTokens.length; i > 0; --i) { address acoToken = acoTokens[i - 1]; uint256 expiryTime = IACOToken(acoToken).expiryTime(); _redeemACOToken(acoToken, expiryTime); } } /** * @dev Function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. */ function redeemACOToken(address acoToken) public override { (,uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); _redeemACOToken(acoToken, expiryTime); } /** * @dev Function to exercise an ACO token negotiated on the pool. * Only ITM ACO tokens are exercisable. * @param acoToken Address of the ACO token. */ function exerciseACOToken(address acoToken) public override { (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); uint256 exercisableAmount = _getExercisableAmount(acoToken); require(exercisableAmount > 0, "ACOPool:: Exercise is not available"); address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 collateralAmount; address _collateral; if (_isCall) { _collateral = _underlying; collateralAmount = exercisableAmount; } else { _collateral = _strikeAsset; collateralAmount = IACOToken(acoToken).getCollateralAmount(exercisableAmount); } uint256 collateralAvailable = _getPoolBalanceOf(_collateral); ACOTokenData storage data = acoTokensData[acoToken]; (bool canExercise, uint256 minIntrinsicValue) = strategy.checkExercise(IACOStrategy.CheckExercise( _underlying, _strikeAsset, _isCall, strikePrice, expiryTime, collateralAmount, collateralAvailable, data.amountPurchased, data.amountSold )); require(canExercise, "ACOPool:: Exercise is not possible"); if (IACOToken(acoToken).allowance(address(this), address(acoFlashExercise)) < exercisableAmount) { _setAuthorizedSpender(acoToken, address(acoFlashExercise)); } acoFlashExercise.flashExercise(acoToken, exercisableAmount, minIntrinsicValue, block.timestamp); uint256 collateralIn = _getPoolBalanceOf(_collateral).sub(collateralAvailable); emit ACOExercise(acoToken, exercisableAmount, collateralIn); } /** * @dev Function to restore the collateral on the pool by selling the other asset balance. */ function restoreCollateral() public override { address _strikeAsset = strikeAsset; address _underlying = underlying; bool _isCall = isCall; uint256 underlyingBalance = _getPoolBalanceOf(_underlying); uint256 strikeAssetBalance = _getPoolBalanceOf(_strikeAsset); uint256 balanceOut; address assetIn; address assetOut; if (_isCall) { balanceOut = strikeAssetBalance; assetIn = _underlying; assetOut = _strikeAsset; } else { balanceOut = underlyingBalance; assetIn = _strikeAsset; assetOut = _underlying; } require(balanceOut > 0, "ACOPool:: No balance"); uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, false); uint256 minToReceive; if (_isCall) { minToReceive = balanceOut.mul(underlyingPrecision).div(acceptablePrice); } else { minToReceive = balanceOut.mul(acceptablePrice).div(underlyingPrecision); } _swapAssetsExactAmountOut(assetOut, assetIn, minToReceive, balanceOut); uint256 collateralIn; if (_isCall) { collateralIn = _getPoolBalanceOf(_underlying).sub(underlyingBalance); } else { collateralIn = _getPoolBalanceOf(_strikeAsset).sub(strikeAssetBalance); } emit RestoreCollateral(balanceOut, collateralIn); } /** * @dev Internal function to swap an ACO token with the pool. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @param restriction Value of the swap restriction. The minimum premium to receive on a selling or the maximum value to pay on a purchase. * @param to Address of the destination. ACO tokens when is buying or strike asset on a selling. * @param deadline UNIX deadline for the swap to be executed. * @return The amount ACO tokens received when is buying or the amount of strike asset received on a selling. */ function _swap( bool isPoolSelling, address acoToken, uint256 tokenAmount, uint256 restriction, address to, uint256 deadline ) internal returns(uint256) { require(block.timestamp <= deadline, "ACOPool:: Swap deadline"); require(to != address(0) && to != acoToken && to != address(this), "ACOPool:: Invalid destination"); (uint256 swapPrice, uint256 protocolFee, uint256 underlyingPrice, uint256 collateralAmount) = _internalQuote(isPoolSelling, acoToken, tokenAmount); uint256 amount; if (isPoolSelling) { amount = _internalSelling(to, acoToken, collateralAmount, tokenAmount, restriction, swapPrice, protocolFee); } else { amount = _internalBuying(to, acoToken, tokenAmount, restriction, swapPrice, protocolFee); } if (protocolFee > 0) { ACOAssetHelper._transferAsset(strikeAsset, feeDestination, protocolFee); } emit Swap(isPoolSelling, msg.sender, acoToken, tokenAmount, swapPrice, protocolFee, underlyingPrice); return amount; } /** * @dev Internal function to quote an ACO token price. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The quote price, the protocol fee charged, the underlying price, and the collateral amount. */ function _internalQuote(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256, uint256, uint256) { require(isPoolSelling || canBuy, "ACOPool:: The pool only sell"); require(tokenAmount > 0, "ACOPool:: Invalid token amount"); (uint256 strikePrice, uint256 expiryTime) = _getValidACOTokenStrikePriceAndExpiration(acoToken); require(expiryTime > block.timestamp, "ACOPool:: ACO token expired"); (uint256 collateralAmount, uint256 collateralAvailable) = _getSizeData(isPoolSelling, acoToken, tokenAmount); (uint256 price, uint256 underlyingPrice,) = _strategyQuote(acoToken, isPoolSelling, strikePrice, expiryTime, collateralAmount, collateralAvailable); price = price.mul(tokenAmount).div(underlyingPrecision); uint256 protocolFee = 0; if (fee > 0) { protocolFee = price.mul(fee).div(100000); if (isPoolSelling) { price = price.add(protocolFee); } else { price = price.sub(protocolFee); } } require(price > 0, "ACOPool:: Invalid quote"); return (price, protocolFee, underlyingPrice, collateralAmount); } /** * @dev Internal function to the size data for a quote. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param acoToken Address of the ACO token. * @param tokenAmount Amount of ACO tokens to swap. * @return The collateral amount and the collateral available on the pool. */ function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; } else { collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); } /** * @dev Internal function to quote on the strategy contract. * @param acoToken Address of the ACO token. * @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. * @param strikePrice ACO token strike price. * @param expiryTime ACO token expiry time on UNIX. * @param collateralAmount Amount of collateral for the order size. * @param collateralAvailable Amount of collateral available on the pool. * @return The quote price, the underlying price and the volatility. */ function _strategyQuote( address acoToken, bool isPoolSelling, uint256 strikePrice, uint256 expiryTime, uint256 collateralAmount, uint256 collateralAvailable ) internal view returns(uint256, uint256, uint256) { ACOTokenData storage data = acoTokensData[acoToken]; return strategy.quote(IACOStrategy.OptionQuote( isPoolSelling, underlying, strikeAsset, isCall, strikePrice, expiryTime, baseVolatility, collateralAmount, collateralAvailable, collateralDeposited, strikeAssetEarnedSelling, strikeAssetSpentBuying, data.amountPurchased, data.amountSold )); } /** * @dev Internal function to sell ACO tokens. * @param to Address of the destination of the ACO tokens. * @param acoToken Address of the ACO token. * @param collateralAmount Order collateral amount. * @param tokenAmount Order token amount. * @param maxPayment Maximum value to be paid for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The ACO token amount sold. */ function _internalSelling( address to, address acoToken, uint256 collateralAmount, uint256 tokenAmount, uint256 maxPayment, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice <= maxPayment, "ACOPool:: Swap restriction"); ACOAssetHelper._callTransferFromERC20(strikeAsset, msg.sender, address(this), swapPrice); uint256 acoBalance = _getPoolBalanceOf(acoToken); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountSold = acoTokenData.amountSold; if (_amountSold == 0 && acoTokenData.amountPurchased == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } if (tokenAmount > acoBalance) { tokenAmount = acoBalance; if (acoBalance > 0) { collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount.sub(acoBalance)); } if (collateralAmount > 0) { address _collateral = collateral(); if (ACOAssetHelper._isEther(_collateral)) { tokenAmount = tokenAmount.add(IACOToken(acoToken).mintPayable{value: collateralAmount}()); } else { if (_amountSold == 0) { _setAuthorizedSpender(_collateral, acoToken); } tokenAmount = tokenAmount.add(IACOToken(acoToken).mint(collateralAmount)); } } } acoTokenData.amountSold = tokenAmount.add(_amountSold); strikeAssetEarnedSelling = swapPrice.sub(protocolFee).add(strikeAssetEarnedSelling); ACOAssetHelper._callTransferERC20(acoToken, to, tokenAmount); return tokenAmount; } /** * @dev Internal function to buy ACO tokens. * @param to Address of the destination of the premium. * @param acoToken Address of the ACO token. * @param tokenAmount Order token amount. * @param minToReceive Minimum value to be received for the ACO tokens. * @param swapPrice The swap price quoted. * @param protocolFee The protocol fee amount. * @return The premium amount transferred. */ function _internalBuying( address to, address acoToken, uint256 tokenAmount, uint256 minToReceive, uint256 swapPrice, uint256 protocolFee ) internal returns(uint256) { require(swapPrice >= minToReceive, "ACOPool:: Swap restriction"); uint256 requiredStrikeAsset = swapPrice.add(protocolFee); if (isCall) { _getStrikeAssetAmount(requiredStrikeAsset); } ACOAssetHelper._callTransferFromERC20(acoToken, msg.sender, address(this), tokenAmount); ACOTokenData storage acoTokenData = acoTokensData[acoToken]; uint256 _amountPurchased = acoTokenData.amountPurchased; if (_amountPurchased == 0 && acoTokenData.amountSold == 0) { acoTokenData.index = acoTokens.length; acoTokens.push(acoToken); } acoTokenData.amountPurchased = tokenAmount.add(_amountPurchased); strikeAssetSpentBuying = requiredStrikeAsset.add(strikeAssetSpentBuying); ACOAssetHelper._transferAsset(strikeAsset, to, swapPrice); return swapPrice; } /** * @dev Internal function to get the normalized deposit amount. * The pool token has always with 18 decimals. * @param collateralAmount Amount of collateral to be deposited. * @return The normalized token amount and the collateral amount. */ function _getNormalizedDepositAmount(uint256 collateralAmount) internal view returns(uint256, uint256) { uint256 basePrecision = isCall ? underlyingPrecision : strikeAssetPrecision; uint256 normalizedAmount; if (basePrecision > POOL_PRECISION) { uint256 adjust = basePrecision.div(POOL_PRECISION); normalizedAmount = collateralAmount.div(adjust); collateralAmount = normalizedAmount.mul(adjust); } else if (basePrecision < POOL_PRECISION) { normalizedAmount = collateralAmount.mul(POOL_PRECISION.div(basePrecision)); } else { normalizedAmount = collateralAmount; } require(normalizedAmount > 0, "ACOPool:: Invalid collateral amount"); return (normalizedAmount, collateralAmount); } /** * @dev Internal function to get an amount of strike asset for the pool. * The pool swaps the collateral for it if necessary. * @param strikeAssetAmount Amount of strike asset required. */ function _getStrikeAssetAmount(uint256 strikeAssetAmount) internal { address _strikeAsset = strikeAsset; uint256 balance = _getPoolBalanceOf(_strikeAsset); if (balance < strikeAssetAmount) { uint256 amountToPurchase = strikeAssetAmount.sub(balance); address _underlying = underlying; uint256 acceptablePrice = strategy.getAcceptableUnderlyingPriceToSwapAssets(_underlying, _strikeAsset, true); uint256 maxPayment = amountToPurchase.mul(underlyingPrecision).div(acceptablePrice); _swapAssetsExactAmountIn(_underlying, _strikeAsset, amountToPurchase, maxPayment); } } /** * @dev Internal function to redeem the collateral from an ACO token. * It redeems the collateral only if the ACO token is expired. * @param acoToken Address of the ACO token. * @param expiryTime ACO token expiry time in UNIX. */ function _redeemACOToken(address acoToken, uint256 expiryTime) internal { if (expiryTime <= block.timestamp) { uint256 collateralIn = 0; if (IACOToken(acoToken).currentCollateralizedTokens(address(this)) > 0) { collateralIn = IACOToken(acoToken).redeem(); } ACOTokenData storage data = acoTokensData[acoToken]; uint256 lastIndex = acoTokens.length - 1; if (lastIndex != data.index) { address last = acoTokens[lastIndex]; acoTokensData[last].index = data.index; acoTokens[data.index] = last; } emit ACORedeem(acoToken, collateralIn, data.amountSold, data.amountPurchased); acoTokens.pop(); delete acoTokensData[acoToken]; } } /** * @dev Internal function to redeem the collateral and the premium from the pool from an account. * @param account Address of the account. * @return The amount of underlying asset received and the amount of strike asset received. */ function _redeem(address account) internal returns(uint256, uint256) { uint256 share = balanceOf(account); require(share > 0, "ACOPool:: Account with no share"); require(!notFinished(), "ACOPool:: Pool is not finished"); redeemACOTokens(); uint256 _totalSupply = totalSupply(); uint256 underlyingBalance = share.mul(_getPoolBalanceOf(underlying)).div(_totalSupply); uint256 strikeAssetBalance = share.mul(_getPoolBalanceOf(strikeAsset)).div(_totalSupply); _callBurn(account, share); if (underlyingBalance > 0) { ACOAssetHelper._transferAsset(underlying, msg.sender, underlyingBalance); } if (strikeAssetBalance > 0) { ACOAssetHelper._transferAsset(strikeAsset, msg.sender, strikeAssetBalance); } emit Redeem(msg.sender, underlyingBalance, strikeAssetBalance); return (underlyingBalance, strikeAssetBalance); } /** * @dev Internal function to burn pool tokens. * @param account Address of the account. * @param tokenAmount Amount of pool tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be sold. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param minAmountIn Minimum amount to be received. * @param amountOut The exact amount to be sold. */ function _swapAssetsExactAmountOut(address assetOut, address assetIn, uint256 minAmountIn, uint256 amountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapExactETHForTokens{value: amountOut}(minAmountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapExactTokensForETH(amountOut, minAmountIn, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapExactTokensForTokens(amountOut, minAmountIn, path, address(this), block.timestamp); } } /** * @dev Internal function to swap assets on the Uniswap V2 with an exact amount of an asset to be purchased. * @param assetOut Address of the asset to be sold. * @param assetIn Address of the asset to be purchased. * @param amountIn The exact amount to be purchased. * @param maxAmountOut Maximum amount to be paid. */ function _swapAssetsExactAmountIn(address assetOut, address assetIn, uint256 amountIn, uint256 maxAmountOut) internal { address[] memory path = new address[](2); if (ACOAssetHelper._isEther(assetOut)) { path[0] = acoFlashExercise.weth(); path[1] = assetIn; uniswapRouter.swapETHForExactTokens{value: maxAmountOut}(amountIn, path, address(this), block.timestamp); } else if (ACOAssetHelper._isEther(assetIn)) { path[0] = assetOut; path[1] = acoFlashExercise.weth(); uniswapRouter.swapTokensForExactETH(amountIn, maxAmountOut, path, address(this), block.timestamp); } else { path[0] = assetOut; path[1] = assetIn; uniswapRouter.swapTokensForExactTokens(amountIn, maxAmountOut, path, address(this), block.timestamp); } } /** * @dev Internal function to set the strategy address. * @param newStrategy Address of the new strategy. */ function _setStrategy(address newStrategy) internal { require(newStrategy.isContract(), "ACOPool:: Invalid strategy"); emit SetStrategy(address(strategy), newStrategy); strategy = IACOStrategy(newStrategy); } /** * @dev Internal function to set the base volatility percentage. (100000 = 100%) * @param newBaseVolatility Value of the new base volatility. */ function _setBaseVolatility(uint256 newBaseVolatility) internal { require(newBaseVolatility > 0, "ACOPool:: Invalid base volatility"); emit SetBaseVolatility(baseVolatility, newBaseVolatility); baseVolatility = newBaseVolatility; } /** * @dev Internal function to set the pool assets precisions. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _setAssetsPrecision(address _underlying, address _strikeAsset) internal { underlyingPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_underlying)); strikeAssetPrecision = 10 ** uint256(ACOAssetHelper._getAssetDecimals(_strikeAsset)); } /** * @dev Internal function to infinite authorize the pool assets on the Uniswap V2 router. * @param _isCall True whether it is a CALL option, otherwise it is PUT. * @param _canBuy True whether the pool can also buy ACO tokens, otherwise it only sells. * @param _uniswapRouter Address of the Uniswap V2 router. * @param _underlying Address of the underlying asset. * @param _strikeAsset Address of the strike asset. */ function _approveAssetsOnRouter( bool _isCall, bool _canBuy, address _uniswapRouter, address _underlying, address _strikeAsset ) internal { if (_isCall) { if (!ACOAssetHelper._isEther(_strikeAsset)) { _setAuthorizedSpender(_strikeAsset, _uniswapRouter); } if (_canBuy && !ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } else if (!ACOAssetHelper._isEther(_underlying)) { _setAuthorizedSpender(_underlying, _uniswapRouter); } } /** * @dev Internal function to infinite authorize a spender on an asset. * @param asset Address of the asset. * @param spender Address of the spender to be authorized. */ function _setAuthorizedSpender(address asset, address spender) internal { ACOAssetHelper._callApproveERC20(asset, spender, MAX_UINT); } /** * @dev Internal function to get the pool balance of an asset. * @param asset Address of the asset. * @return The pool balance. */ function _getPoolBalanceOf(address asset) internal view returns(uint256) { return ACOAssetHelper._getAssetBalanceOf(asset, address(this)); } /** * @dev Internal function to get the exercible amount of an ACO token. * @param acoToken Address of the ACO token. * @return The exercisable amount. */ function _getExercisableAmount(address acoToken) internal view returns(uint256) { uint256 balance = _getPoolBalanceOf(acoToken); if (balance > 0) { uint256 collaterized = IACOToken(acoToken).currentCollateralizedTokens(address(this)); if (balance > collaterized) { return balance.sub(collaterized); } } return 0; } /** * @dev Internal function to get an accepted ACO token by the pool. * @param acoToken Address of the ACO token. * @return The ACO token strike price, and the ACO token expiration. */ function _getValidACOTokenStrikePriceAndExpiration(address acoToken) internal view returns(uint256, uint256) { (address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime) = acoFactory.acoTokenData(acoToken); require( _underlying == underlying && _strikeAsset == strikeAsset && _isCall == isCall && _strikePrice >= minStrikePrice && _strikePrice <= maxStrikePrice && _expiryTime >= minExpiration && _expiryTime <= maxExpiration, "ACOPool:: Invalid ACO Token" ); return (_strikePrice, _expiryTime); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO POOL UNDERLYING_SYMBOL-STRIKE_ASSET_SYMBOL-TYPE-{ONLY_SELL}-MIN_STRIKE_PRICE-MAX_STRIKE_PRICE-MIN_EXPIRATION-MAX_EXPIRATION * @return The token name. */ function _name() internal view returns(string memory) { uint8 strikeDecimals = ACOAssetHelper._getAssetDecimals(strikeAsset); string memory strikePriceFormatted; if (minStrikePrice != maxStrikePrice) { strikePriceFormatted = string(abi.encodePacked(ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals), "-", ACONameFormatter.formatNumber(maxStrikePrice, strikeDecimals))); } else { strikePriceFormatted = ACONameFormatter.formatNumber(minStrikePrice, strikeDecimals); } string memory dateFormatted; if (minExpiration != maxExpiration) { dateFormatted = string(abi.encodePacked(ACONameFormatter.formatTime(minExpiration), "-", ACONameFormatter.formatTime(maxExpiration))); } else { dateFormatted = ACONameFormatter.formatTime(minExpiration); } return string(abi.encodePacked( "ACO POOL ", ACOAssetHelper._getAssetSymbol(underlying), "-", ACOAssetHelper._getAssetSymbol(strikeAsset), "-", ACONameFormatter.formatType(isCall), (canBuy ? "" : "-SELL"), "-", strikePriceFormatted, "-", dateFormatted )); } }
* @dev Internal function to the size data for a quote. @param isPoolSelling True whether the pool is selling an ACO token, otherwise the pool is buying. @param acoToken Address of the ACO token. @param tokenAmount Amount of ACO tokens to swap. @return The collateral amount and the collateral available on the pool./
function _getSizeData(bool isPoolSelling, address acoToken, uint256 tokenAmount) internal view returns(uint256, uint256) { uint256 collateralAmount; uint256 collateralAvailable; if (isCall) { collateralAvailable = _getPoolBalanceOf(underlying); collateralAmount = tokenAmount; collateralAvailable = _getPoolBalanceOf(strikeAsset); collateralAmount = IACOToken(acoToken).getCollateralAmount(tokenAmount); require(collateralAmount > 0, "ACOPool:: Token amount is too small"); } require(!isPoolSelling || collateralAmount <= collateralAvailable, "ACOPool:: Insufficient liquidity"); return (collateralAmount, collateralAvailable); }
48,877
[ 1, 3061, 445, 358, 326, 963, 501, 364, 279, 3862, 18, 225, 353, 2864, 55, 1165, 310, 1053, 2856, 326, 2845, 353, 357, 2456, 392, 432, 3865, 1147, 16, 3541, 326, 2845, 353, 30143, 310, 18, 225, 1721, 83, 1345, 5267, 434, 326, 432, 3865, 1147, 18, 225, 1147, 6275, 16811, 434, 432, 3865, 2430, 358, 7720, 18, 327, 1021, 4508, 2045, 287, 3844, 471, 326, 4508, 2045, 287, 2319, 603, 326, 2845, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 588, 1225, 751, 12, 6430, 353, 2864, 55, 1165, 310, 16, 1758, 1721, 83, 1345, 16, 2254, 5034, 1147, 6275, 13, 2713, 1476, 1135, 12, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 2254, 5034, 4508, 2045, 287, 6275, 31, 203, 3639, 2254, 5034, 4508, 2045, 287, 5268, 31, 203, 3639, 309, 261, 291, 1477, 13, 288, 203, 5411, 4508, 2045, 287, 5268, 273, 389, 588, 2864, 13937, 951, 12, 9341, 6291, 1769, 203, 5411, 4508, 2045, 287, 6275, 273, 1147, 6275, 31, 7010, 5411, 4508, 2045, 287, 5268, 273, 389, 588, 2864, 13937, 951, 12, 701, 2547, 6672, 1769, 203, 5411, 4508, 2045, 287, 6275, 273, 467, 2226, 51, 1345, 12, 24363, 1345, 2934, 588, 13535, 2045, 287, 6275, 12, 2316, 6275, 1769, 203, 5411, 2583, 12, 12910, 2045, 287, 6275, 405, 374, 16, 315, 2226, 51, 2864, 2866, 3155, 3844, 353, 4885, 5264, 8863, 203, 3639, 289, 203, 3639, 2583, 12, 5, 291, 2864, 55, 1165, 310, 747, 4508, 2045, 287, 6275, 1648, 4508, 2045, 287, 5268, 16, 315, 2226, 51, 2864, 2866, 22085, 11339, 4501, 372, 24237, 8863, 203, 540, 203, 3639, 327, 261, 12910, 2045, 287, 6275, 16, 4508, 2045, 287, 5268, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.15; import {IForwarderRegistry} from "./../../../../metatx/interfaces/IForwarderRegistry.sol"; import {ERC721DeliverableOnceFacet} from "./../../../../token/ERC721/facets/ERC721DeliverableOnceFacet.sol"; /// @title ERC721DeliverableOnceFacetMock contract ERC721DeliverableOnceFacetMock is ERC721DeliverableOnceFacet { constructor(IForwarderRegistry forwarderRegistry) ERC721DeliverableOnceFacet(forwarderRegistry) {} function __msgData() external view returns (bytes calldata) { return _msgData(); } }
@title ERC721DeliverableOnceFacetMock
contract ERC721DeliverableOnceFacetMock is ERC721DeliverableOnceFacet { pragma solidity 0.8.15; import {IForwarderRegistry} from "./../../../../metatx/interfaces/IForwarderRegistry.sol"; import {ERC721DeliverableOnceFacet} from "./../../../../token/ERC721/facets/ERC721DeliverableOnceFacet.sol"; constructor(IForwarderRegistry forwarderRegistry) ERC721DeliverableOnceFacet(forwarderRegistry) {} function __msgData() external view returns (bytes calldata) { return _msgData(); } }
12,541,226
[ 1, 654, 39, 27, 5340, 20813, 429, 12212, 11137, 9865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 27, 5340, 20813, 429, 12212, 11137, 9865, 353, 4232, 39, 27, 5340, 20813, 429, 12212, 11137, 288, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3600, 31, 203, 5666, 288, 45, 30839, 4243, 97, 628, 25165, 16644, 16644, 10578, 270, 92, 19, 15898, 19, 45, 30839, 4243, 18, 18281, 14432, 203, 5666, 288, 654, 39, 27, 5340, 20813, 429, 12212, 11137, 97, 628, 25165, 16644, 16644, 2316, 19, 654, 39, 27, 5340, 19, 11639, 2413, 19, 654, 39, 27, 5340, 20813, 429, 12212, 11137, 18, 18281, 14432, 203, 565, 3885, 12, 45, 30839, 4243, 364, 20099, 4243, 13, 4232, 39, 27, 5340, 20813, 429, 12212, 11137, 12, 1884, 20099, 4243, 13, 2618, 203, 565, 445, 1001, 3576, 751, 1435, 3903, 1476, 1135, 261, 3890, 745, 892, 13, 288, 203, 3639, 327, 389, 3576, 751, 5621, 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 ]
./full_match/1/0x1bAC1E3003668fc0Cc4838DD3Fb62E8C2671b271/sources/browser/TorroDao.sol
Emit event that a proposal has been voted for.
emit Vote(id);
3,118,689
[ 1, 17982, 871, 716, 279, 14708, 711, 2118, 331, 16474, 364, 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, 1377, 3626, 27540, 12, 350, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/modules/core/MarketManagerModule.sol
* @inheritdoc IMarketManagerModule/
function getMarketReportedDebt(uint128 marketId) external view override returns (uint256) { return Market.load(marketId).getReportedDebt(); }
16,517,013
[ 1, 36, 10093, 467, 3882, 278, 1318, 3120, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23232, 278, 426, 1798, 758, 23602, 12, 11890, 10392, 13667, 548, 13, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 6622, 278, 18, 945, 12, 27151, 548, 2934, 588, 426, 1798, 758, 23602, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x2b265B8336456158D2Ed4aD03B8d611079714F23/sources/src/Magai/Magai.sol
100% of the balance assigned to this contract
uint256 liquidityTokens = balanceOf(address(this));
16,488,872
[ 1, 6625, 9, 434, 326, 11013, 6958, 358, 333, 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 ]
[ 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, 202, 11890, 5034, 4501, 372, 24237, 5157, 273, 11013, 951, 12, 2867, 12, 2211, 10019, 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 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/multipleTransfer.sol pragma solidity >=0.6.0 <0.8.0; contract MultipleTransfer is Ownable { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; constructor ( IERC20 token_ ) public { _token = token_; } /** * @return the token being held. */ function token() public view virtual returns (IERC20) { return _token; } /** * @return the current balance. */ function balanceOf() public view virtual returns (uint256) { return token().balanceOf(address(this)); } function sendBackTokens() public onlyOwner { token().safeTransfer(owner(), balanceOf()); } function multipleTransfer(address[] memory recipients, uint256[] memory amounts) public onlyOwner { require(recipients.length == amounts.length, "recipients length must be equal to amounts"); for(uint256 i = 0; i < recipients.length; i++) { token().safeTransfer(recipients[i], amounts[i]); } } }
ERC20 basic token contract being held
contract MultipleTransfer is Ownable { using SafeERC20 for IERC20; IERC20 private _token; constructor ( IERC20 token_ ) public { _token = token_; } function token() public view virtual returns (IERC20) { return _token; } function balanceOf() public view virtual returns (uint256) { return token().balanceOf(address(this)); } function sendBackTokens() public onlyOwner { token().safeTransfer(owner(), balanceOf()); } function multipleTransfer(address[] memory recipients, uint256[] memory amounts) public onlyOwner { require(recipients.length == amounts.length, "recipients length must be equal to amounts"); for(uint256 i = 0; i < recipients.length; i++) { token().safeTransfer(recipients[i], amounts[i]); } } function multipleTransfer(address[] memory recipients, uint256[] memory amounts) public onlyOwner { require(recipients.length == amounts.length, "recipients length must be equal to amounts"); for(uint256 i = 0; i < recipients.length; i++) { token().safeTransfer(recipients[i], amounts[i]); } } }
571,699
[ 1, 654, 39, 3462, 5337, 1147, 6835, 3832, 15770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 13531, 5912, 353, 14223, 6914, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 467, 654, 39, 3462, 3238, 389, 2316, 31, 203, 203, 225, 3885, 261, 203, 565, 467, 654, 39, 3462, 1147, 67, 203, 203, 225, 262, 1071, 288, 203, 565, 389, 2316, 273, 1147, 67, 31, 203, 225, 289, 203, 203, 225, 445, 1147, 1435, 1071, 1476, 5024, 1135, 261, 45, 654, 39, 3462, 13, 288, 203, 565, 327, 389, 2316, 31, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 1435, 1071, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 1147, 7675, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 225, 289, 203, 203, 225, 445, 1366, 2711, 5157, 1435, 1071, 1338, 5541, 288, 203, 565, 1147, 7675, 4626, 5912, 12, 8443, 9334, 11013, 951, 10663, 203, 225, 289, 203, 203, 225, 445, 3229, 5912, 12, 2867, 8526, 3778, 12045, 16, 2254, 5034, 8526, 3778, 30980, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 27925, 18, 2469, 422, 30980, 18, 2469, 16, 315, 27925, 769, 1297, 506, 3959, 358, 30980, 8863, 203, 565, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 12045, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 2316, 7675, 4626, 5912, 12, 27925, 63, 77, 6487, 30980, 63, 77, 19226, 203, 565, 289, 203, 225, 289, 203, 225, 445, 3229, 5912, 12, 2867, 8526, 3778, 12045, 16, 2254, 5034, 8526, 3778, 30980, 13, 1071, 1338, 5541, 288, 203, 565, 2583, 12, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma experimental ABIEncoderV2; import "contracts/ImpartialSelection.sol"; import "contracts/ExactDollarPartitionNoStorage.sol"; /// @title Impartial Selection noStorage implementation /// @author Giovanni Rescinito /// @notice smart contract implementing the system proposed, using no data structures for storing scores contract ImpartialSelectionNoStorage is ImpartialSelection{ mapping(uint=>bool) private revealed; // dictionary containing information about whether a proposal's commitment was revealed /// @notice creates a new instance of the contract /// @param tokenAddress address of the PET token to connect to the contract constructor(address tokenAddress) ImpartialSelection(tokenAddress) public{} /// @notice ends the reveal phase and checks that everyone submitted their scores function endRevealPhase() public override{ super.endRevealPhase(); ExactDollarPartitionNoStorage.finalizeScores(revealed,partition,scoreAccumulated); } /// @notice performs the reveal operation and updates the scores /// @param tokenId token used during the commitment phase, to retrieve the corresponding commitment /// @param randomness randomness used to generate the commitment /// @param evaluations scores used to generate the commitment /// @return the evaluations provided function revealEvaluations(uint tokenId, uint randomness, uint[] calldata evaluations) public override returns (uint[] memory){ uint id = Proposals.getIdFromToken(proposals,tokenId); require(!revealed[id], "Already revealed"); uint[] memory assignments = super.revealEvaluations(tokenId,randomness,evaluations); ExactDollarPartitionNoStorage.addScores(revealed,scoreAccumulated,id, assignments, evaluations); return evaluations; } }
@notice ends the reveal phase and checks that everyone submitted their scores
function endRevealPhase() public override{ super.endRevealPhase(); ExactDollarPartitionNoStorage.finalizeScores(revealed,partition,scoreAccumulated); }
2,546,133
[ 1, 5839, 326, 283, 24293, 6855, 471, 4271, 716, 3614, 476, 9638, 3675, 8474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 679, 426, 24293, 11406, 1435, 1071, 3849, 95, 203, 3639, 2240, 18, 409, 426, 24293, 11406, 5621, 203, 3639, 30794, 40, 25442, 7003, 2279, 3245, 18, 30343, 20037, 12, 266, 537, 18931, 16, 10534, 16, 6355, 8973, 5283, 690, 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 ]
./partial_match/1/0x34A542aCD8A717B5933228Ae3C554B1328F36e14/sources/ERC20ByMetadrop.sol
Approval cannot be given to the zero address.
error ApproveToTheZeroAddress();
2,631,338
[ 1, 23461, 2780, 506, 864, 358, 326, 3634, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 555, 1716, 685, 537, 774, 1986, 7170, 1887, 5621, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x208426c2B281aC34f7005A03f638F43C6489505e/sources/contracts/lib/balancer/configurable-rights-pool/contracts/ConfigurableRightsPool.sol
Hold the parameters used in updateWeightsGradually
SmartPoolManager.GradualUpdateParams public gradualUpdate;
12,287,933
[ 1, 20586, 326, 1472, 1399, 316, 1089, 16595, 14571, 2544, 1230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 19656, 2864, 1318, 18, 30420, 1462, 1891, 1370, 1071, 6058, 1462, 1891, 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 ]
./full_match/5/0xc1991bF5359f0BCe4f936e718353b07DeE97DaBa/sources/contracts/Kingdomly Shitcoins/GenericShitcoinETH(test).sol
Updates the buy and sell taxes to the new inputs
function updateTaxes(uint256 _buyTax, uint256 _sellTax) public onlyOwner{ require(_buyTax >= 0 && _sellTax >= 0, "Cant input a negative tax"); buyTax = _buyTax; sellTax = _sellTax; }
1,870,485
[ 1, 5121, 326, 30143, 471, 357, 80, 5320, 281, 358, 326, 394, 4540, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 7731, 281, 12, 11890, 5034, 389, 70, 9835, 7731, 16, 2254, 5034, 389, 87, 1165, 7731, 13, 1071, 1338, 5541, 95, 203, 3639, 2583, 24899, 70, 9835, 7731, 1545, 374, 597, 389, 87, 1165, 7731, 1545, 374, 16, 315, 39, 970, 810, 279, 6092, 5320, 8863, 203, 203, 3639, 30143, 7731, 273, 389, 70, 9835, 7731, 31, 203, 3639, 357, 80, 7731, 273, 389, 87, 1165, 7731, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/drafts/IERC20Permit.sol"; import "../external/ERC721PresetMinterPauserAutoId.sol"; import "../interfaces/IERC20withDec.sol"; import "../interfaces/ISeniorPool.sol"; import "../interfaces/IStakingRewards.sol"; import "../protocol/core/GoldfinchConfig.sol"; import "../protocol/core/ConfigHelper.sol"; import "../protocol/core/BaseUpgradeablePausable.sol"; import "../library/StakingRewardsVesting.sol"; // solhint-disable-next-line max-states-count contract StakingRewards is ERC721PresetMinterPauserAutoIdUpgradeSafe, ReentrancyGuardUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20withDec; using SafeERC20 for IERC20; using ConfigHelper for GoldfinchConfig; using StakingRewardsVesting for StakingRewardsVesting.Rewards; enum LockupPeriod { SixMonths, TwelveMonths, TwentyFourMonths } enum StakedPositionType { Fidu, CurveLP } struct StakedPosition { // @notice Staked amount denominated in `stakingToken().decimals()` uint256 amount; // @notice Struct describing rewards owed with vesting StakingRewardsVesting.Rewards rewards; // @notice Multiplier applied to staked amount when locking up position uint256 leverageMultiplier; // @notice Time in seconds after which position can be unstaked uint256 lockedUntil; // @notice Type of the staked position StakedPositionType positionType; // @notice Multiplier applied to staked amount to denominate in `baseStakingToken().decimals()` // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1. // If you need this field, use `safeEffectiveMultiplier()`, which correctly handles old staked positions. uint256 unsafeEffectiveMultiplier; // @notice Exchange rate applied to staked amount to denominate in `baseStakingToken().decimals()` // @dev This field should not be used directly; it may be 0 for staked positions created prior to GIP-1. // If you need this field, use `safeBaseTokenExchangeRate()`, which correctly handles old staked positions. uint256 unsafeBaseTokenExchangeRate; } /* ========== EVENTS =================== */ event RewardsParametersUpdated( address indexed who, uint256 targetCapacity, uint256 minRate, uint256 maxRate, uint256 minRateAtPercent, uint256 maxRateAtPercent ); event TargetCapacityUpdated(address indexed who, uint256 targetCapacity); event VestingScheduleUpdated(address indexed who, uint256 vestingLength); event MinRateUpdated(address indexed who, uint256 minRate); event MaxRateUpdated(address indexed who, uint256 maxRate); event MinRateAtPercentUpdated(address indexed who, uint256 minRateAtPercent); event MaxRateAtPercentUpdated(address indexed who, uint256 maxRateAtPercent); event EffectiveMultiplierUpdated(address indexed who, StakedPositionType positionType, uint256 multiplier); /* ========== STATE VARIABLES ========== */ uint256 private constant MULTIPLIER_DECIMALS = 1e18; bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); bytes32 public constant ZAPPER_ROLE = keccak256("ZAPPER_ROLE"); GoldfinchConfig public config; /// @notice The block timestamp when rewards were last checkpointed uint256 public lastUpdateTime; /// @notice Accumulated rewards per token at the last checkpoint uint256 public accumulatedRewardsPerToken; /// @notice Total rewards available for disbursement at the last checkpoint, denominated in `rewardsToken()` uint256 public rewardsAvailable; /// @notice StakedPosition tokenId => accumulatedRewardsPerToken at the position's last checkpoint mapping(uint256 => uint256) public positionToAccumulatedRewardsPerToken; /// @notice Desired supply of staked tokens. The reward rate adjusts in a range /// around this value to incentivize staking or unstaking to maintain it. uint256 public targetCapacity; /// @notice The minimum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public minRate; /// @notice The maximum total disbursed rewards per second, denominated in `rewardsToken()` uint256 public maxRate; /// @notice The percent of `targetCapacity` at which the reward rate reaches `maxRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public maxRateAtPercent; /// @notice The percent of `targetCapacity` at which the reward rate reaches `minRate`. /// Represented with `MULTIPLIER_DECIMALS`. uint256 public minRateAtPercent; /// @notice The duration in seconds over which rewards vest uint256 public vestingLength; /// @dev Supply of staked tokens, denominated in `stakingToken().decimals()` /// @dev Note that due to the use of `unsafeBaseTokenExchangeRate` and `unsafeEffectiveMultiplier` on /// a StakedPosition, the sum of `amount` across all staked positions will not necessarily /// equal this `totalStakedSupply` value; the purpose of the base token exchange rate and /// the effective multiplier is to enable calculation of an "effective amount" -- which is /// what this `totalStakedSupply` represents the sum of. uint256 public totalStakedSupply; /// @dev UNUSED (definition kept for storage slot) uint256 private totalLeveragedStakedSupply; /// @dev UNUSED (definition kept for storage slot) mapping(LockupPeriod => uint256) private leverageMultipliers; /// @dev NFT tokenId => staked position mapping(uint256 => StakedPosition) public positions; /// @dev A mapping of staked position types to multipliers used to denominate positions /// in `baseStakingToken()`. Represented with `MULTIPLIER_DECIMALS`. mapping(StakedPositionType => uint256) private effectiveMultipliers; // solhint-disable-next-line func-name-mixedcase function __initialize__(address owner, GoldfinchConfig _config) external initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained("Goldfinch V2 LP Staking Tokens", "GFI-V2-LPS"); __ERC721Pausable_init_unchained(); __AccessControl_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); _setupRole(OWNER_ROLE, owner); _setupRole(PAUSER_ROLE, owner); _setRoleAdmin(PAUSER_ROLE, OWNER_ROLE); _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); config = _config; vestingLength = 365 days; } function initZapperRole() external onlyAdmin { _setRoleAdmin(ZAPPER_ROLE, OWNER_ROLE); } /* ========== VIEWS ========== */ /// @notice Returns the staked balance of a given position token. /// @dev The value returned is the bare amount, not the effective amount. The bare amount represents /// the number of tokens the user has staked for a given position. /// @param tokenId A staking position token ID /// @return Amount of staked tokens denominated in `stakingToken().decimals()` function stakedBalanceOf(uint256 tokenId) external view returns (uint256) { return positions[tokenId].amount; } /// @notice The address of the token being disbursed as rewards function rewardsToken() internal view returns (IERC20withDec) { return config.getGFI(); } /// @notice The address of the token that is staked for a given position type function stakingToken(StakedPositionType positionType) internal view returns (IERC20) { if (positionType == StakedPositionType.CurveLP) { return IERC20(config.getFiduUSDCCurveLP().token()); } return config.getFidu(); } /// @notice The address of the base token used to denominate staking rewards function baseStakingToken() internal view returns (IERC20withDec) { return config.getFidu(); } /// @notice The additional rewards earned per token, between the provided time and the last /// time rewards were checkpointed, given the prevailing `rewardRate()`. This amount is limited /// by the amount of rewards that are available for distribution; if there aren't enough /// rewards in the balance of this contract, then we shouldn't be giving them out. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function _additionalRewardsPerTokenSinceLastUpdate(uint256 time) internal view returns (uint256) { /// @dev IT: Invalid end time for range require(time >= lastUpdateTime, "IT"); if (totalStakedSupply == 0) { return 0; } uint256 rewardsSinceLastUpdate = Math.min(time.sub(lastUpdateTime).mul(rewardRate()), rewardsAvailable); uint256 additionalRewardsPerToken = rewardsSinceLastUpdate.mul(stakingAndRewardsTokenMantissa()).div( totalStakedSupply ); // Prevent perverse, infinite-mint scenario where totalStakedSupply is a fraction of a token. // Since it's used as the denominator, this could make additionalRewardPerToken larger than the total number // of tokens that should have been disbursed in the elapsed time. The attacker would need to find // a way to reduce totalStakedSupply while maintaining a staked position of >= 1. // See: https://twitter.com/Mudit__Gupta/status/1409463917290557440 if (additionalRewardsPerToken > rewardsSinceLastUpdate) { return 0; } return additionalRewardsPerToken; } /// @notice Returns accumulated rewards per token up to the current block timestamp /// @return Amount of rewards denominated in `rewardsToken().decimals()` function rewardPerToken() public view returns (uint256) { return accumulatedRewardsPerToken.add(_additionalRewardsPerTokenSinceLastUpdate(block.timestamp)); } /// @notice Returns rewards earned by a given position token from its last checkpoint up to the /// current block timestamp. /// @param tokenId A staking position token ID /// @return Amount of rewards denominated in `rewardsToken().decimals()` function earnedSinceLastCheckpoint(uint256 tokenId) public view returns (uint256) { return _positionToEffectiveAmount(positions[tokenId]) .mul(rewardPerToken().sub(positionToAccumulatedRewardsPerToken[tokenId])) .div(stakingAndRewardsTokenMantissa()); } function totalOptimisticClaimable(address owner) external view returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < balanceOf(owner); i++) { uint256 tokenId = tokenOfOwnerByIndex(owner, i); result = result.add(optimisticClaimable(tokenId)); } return result; } function optimisticClaimable(uint256 tokenId) public view returns (uint256) { return earnedSinceLastCheckpoint(tokenId).add(claimableRewards(tokenId)); } /// @notice Returns the rewards claimable by a given position token at the most recent checkpoint, taking into /// account vesting schedule. /// @return rewards Amount of rewards denominated in `rewardsToken()` function claimableRewards(uint256 tokenId) public view returns (uint256 rewards) { return positions[tokenId].rewards.claimable(); } /// @notice Returns the rewards that will have vested for some position with the given params. /// @return rewards Amount of rewards denominated in `rewardsToken()` function totalVestedAt( uint256 start, uint256 end, uint256 time, uint256 grantedAmount ) external pure returns (uint256 rewards) { return StakingRewardsVesting.totalVestedAt(start, end, time, grantedAmount); } /// @notice Number of rewards, in `rewardsToken().decimals()`, to disburse each second function rewardRate() internal view returns (uint256) { // The reward rate can be thought of as a piece-wise function: // // let intervalStart = (maxRateAtPercent * targetCapacity), // intervalEnd = (minRateAtPercent * targetCapacity), // x = totalStakedSupply // in // if x < intervalStart // y = maxRate // if x > intervalEnd // y = minRate // else // y = maxRate - (maxRate - minRate) * (x - intervalStart) / (intervalEnd - intervalStart) // // See an example here: // solhint-disable-next-line max-line-length // https://www.wolframalpha.com/input/?i=Piecewise%5B%7B%7B1000%2C+x+%3C+50%7D%2C+%7B100%2C+x+%3E+300%7D%2C+%7B1000+-+%281000+-+100%29+*+%28x+-+50%29+%2F+%28300+-+50%29+%2C+50+%3C+x+%3C+300%7D%7D%5D // // In that example: // maxRateAtPercent = 0.5, minRateAtPercent = 3, targetCapacity = 100, maxRate = 1000, minRate = 100 uint256 intervalStart = targetCapacity.mul(maxRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 intervalEnd = targetCapacity.mul(minRateAtPercent).div(MULTIPLIER_DECIMALS); uint256 x = totalStakedSupply; // Subsequent computation would overflow if (intervalEnd <= intervalStart) { return 0; } if (x < intervalStart) { return maxRate; } if (x > intervalEnd) { return minRate; } return maxRate.sub(maxRate.sub(minRate).mul(x.sub(intervalStart)).div(intervalEnd.sub(intervalStart))); } function _positionToEffectiveAmount(StakedPosition storage position) internal view returns (uint256) { return toEffectiveAmount(position.amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position)); } /// @notice Calculates the effective amount given the amount, (safe) base token exchange rate, /// and (safe) effective multiplier for a position /// @param amount The amount of staked tokens /// @param safeBaseTokenExchangeRate The (safe) base token exchange rate. See @dev comment below. /// @param safeEffectiveMultiplier The (safe) effective multiplier. See @dev comment below. /// @dev Do NOT pass in the unsafeBaseTokenExchangeRate or unsafeEffectiveMultiplier in storage. /// Convert it to safe values using `safeBaseTokenExchangeRate()` and `safeEffectiveMultiplier()` // before calling this function. function toEffectiveAmount( uint256 amount, uint256 safeBaseTokenExchangeRate, uint256 safeEffectiveMultiplier ) internal pure returns (uint256) { // Both the exchange rate and the effective multiplier are denominated in MULTIPLIER_DECIMALS return amount.mul(safeBaseTokenExchangeRate).mul(safeEffectiveMultiplier).div(MULTIPLIER_DECIMALS).div( MULTIPLIER_DECIMALS ); } /// @dev We overload the responsibility of this function -- i.e. returning a value that can be /// used for both the `stakingToken()` mantissa and the `rewardsToken()` mantissa --, rather than have /// multiple distinct functions for that purpose, in order to reduce contract size. We rely on a unit /// test to ensure that the tokens' mantissas are indeed equal and therefore that this approach works. function stakingAndRewardsTokenMantissa() internal view returns (uint256) { return uint256(10)**baseStakingToken().decimals(); } /// @notice The amount of rewards currently being earned per token per second. This amount takes into /// account how many rewards are actually available for disbursal -- unlike `rewardRate()` which does not. /// This function is intended for public consumption, to know the rate at which rewards are being /// earned, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function currentEarnRatePerToken() public view returns (uint256) { uint256 time = block.timestamp == lastUpdateTime ? block.timestamp + 1 : block.timestamp; uint256 elapsed = time.sub(lastUpdateTime); return _additionalRewardsPerTokenSinceLastUpdate(time).div(elapsed); } /// @notice The amount of rewards currently being earned per second, for a given position. This function /// is intended for public consumption, to know the rate at which rewards are being earned /// for a given position, and not as an input to the mutative calculations in this contract. /// @return Amount of rewards denominated in `rewardsToken().decimals()`. function positionCurrentEarnRate(uint256 tokenId) external view returns (uint256) { return currentEarnRatePerToken().mul(_positionToEffectiveAmount(positions[tokenId])).div( stakingAndRewardsTokenMantissa() ); } /* ========== MUTATIVE FUNCTIONS ========== */ /// @notice Stake `stakingToken()` to earn rewards. When you call this function, you'll receive an /// an NFT representing your staked position. You can present your NFT to `getReward` or `unstake` /// to claim rewards or unstake your tokens respectively. Rewards vest over a schedule. /// @dev This function checkpoints rewards. /// @param amount The amount of `stakingToken()` to stake /// @param positionType The type of the staked position function stake(uint256 amount, StakedPositionType positionType) external nonReentrant whenNotPaused updateReward(0) { _stake(msg.sender, msg.sender, amount, positionType); } /// @notice Deposit to SeniorPool and stake your shares in the same transaction. /// @param usdcAmount The amount of USDC to deposit into the senior pool. All shares from deposit /// will be staked. function depositAndStake(uint256 usdcAmount) public nonReentrant whenNotPaused updateReward(0) { /// @dev GL: This address has not been go-listed require(isGoListed(), "GL"); IERC20withDec usdc = config.getUSDC(); usdc.safeTransferFrom(msg.sender, address(this), usdcAmount); ISeniorPool seniorPool = config.getSeniorPool(); usdc.safeIncreaseAllowance(address(seniorPool), usdcAmount); uint256 fiduAmount = seniorPool.deposit(usdcAmount); uint256 tokenId = _stake(address(this), msg.sender, fiduAmount, StakedPositionType.Fidu); emit DepositedAndStaked(msg.sender, usdcAmount, tokenId, fiduAmount); } /// @notice Identical to `depositAndStake`, except it allows for a signature to be passed that permits /// this contract to move funds on behalf of the user. /// @param usdcAmount The amount of USDC to deposit /// @param v secp256k1 signature component /// @param r secp256k1 signature component /// @param s secp256k1 signature component function depositWithPermitAndStake( uint256 usdcAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), usdcAmount, deadline, v, r, s); depositAndStake(usdcAmount); } /// @notice Deposits FIDU and USDC to Curve on behalf of the user. The Curve LP tokens will be minted /// directly to the user's address /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function depositToCurve(uint256 fiduAmount, uint256 usdcAmount) external nonReentrant whenNotPaused { uint256 curveLPTokens = _depositToCurve(msg.sender, msg.sender, fiduAmount, usdcAmount); emit DepositedToCurve(msg.sender, fiduAmount, usdcAmount, curveLPTokens); } function depositToCurveAndStake(uint256 fiduAmount, uint256 usdcAmount) external { depositToCurveAndStakeFrom(msg.sender, fiduAmount, usdcAmount); } /// @notice Deposit to FIDU and USDC into the Curve LP, and stake your Curve LP tokens in the same transaction. /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function depositToCurveAndStakeFrom( address nftRecipient, uint256 fiduAmount, uint256 usdcAmount ) public nonReentrant whenNotPaused updateReward(0) { // Add liquidity to Curve. The Curve LP tokens will be minted under StakingRewards uint256 curveLPTokens = _depositToCurve(msg.sender, address(this), fiduAmount, usdcAmount); // Stake the Curve LP tokens on behalf of the user uint256 tokenId = _stake(address(this), nftRecipient, curveLPTokens, StakedPositionType.CurveLP); emit DepositedToCurveAndStaked(msg.sender, fiduAmount, usdcAmount, tokenId, curveLPTokens); } /// @notice Deposit to FIDU and USDC into the Curve LP. Returns the amount of Curve LP tokens minted, /// which is denominated in 1e18. /// @param depositor The address of the depositor (i.e. the current owner of the FIDU and USDC to deposit) /// @param lpTokensRecipient The receipient of the resulting LP tokens /// @param fiduAmount The amount of FIDU to deposit /// @param usdcAmount The amount of USDC to deposit function _depositToCurve( address depositor, address lpTokensRecipient, uint256 fiduAmount, uint256 usdcAmount ) internal returns (uint256) { /// @dev ZERO: Cannot stake 0 require(fiduAmount > 0 || usdcAmount > 0, "ZERO"); IERC20withDec usdc = config.getUSDC(); IERC20withDec fidu = config.getFidu(); ICurveLP curveLP = config.getFiduUSDCCurveLP(); // Transfer FIDU and USDC from depositor to StakingRewards, and allow the Curve LP contract to spend // this contract's FIDU and USDC if (fiduAmount > 0) { fidu.safeTransferFrom(depositor, address(this), fiduAmount); fidu.safeIncreaseAllowance(address(curveLP), fiduAmount); } if (usdcAmount > 0) { usdc.safeTransferFrom(depositor, address(this), usdcAmount); usdc.safeIncreaseAllowance(address(curveLP), usdcAmount); } // We will allow up to 10% slippage, so minMintAmount should be at least 90% uint256 minMintAmount = curveLP.calc_token_amount([fiduAmount, usdcAmount]).mul(9).div(10); // Add liquidity to Curve. The Curve LP tokens will be minted under the `lpTokensRecipient`. // The `add_liquidity()` function returns the number of LP tokens minted, denominated in 1e18. // // solhint-disable-next-line max-line-length // https://github.com/curvefi/curve-factory/blob/ab5e7f6934c0dcc3ad06ccda4d6b35ffbbc99d42/contracts/implementations/plain-4/Plain4Basic.vy#L76 // https://curve.readthedocs.io/factory-pools.html#StableSwap.decimals // // It would perhaps be ideal to do our own enforcement of `minMintAmount`, but given the Curve // contract is non-upgradeable and we are satisfied with its implementation, we do not. return curveLP.add_liquidity([fiduAmount, usdcAmount], minMintAmount, false, lpTokensRecipient); } /// @notice Returns the effective multiplier for a given position. Defaults to 1 for all staked /// positions created prior to GIP-1 (before the `unsafeEffectiveMultiplier` field was added). /// @dev Always use this method to get the effective multiplier to ensure proper handling of /// old staked positions. function safeEffectiveMultiplier(StakedPosition storage position) internal view returns (uint256) { if (position.unsafeEffectiveMultiplier > 0) { return position.unsafeEffectiveMultiplier; } return MULTIPLIER_DECIMALS; // 1x } /// @notice Returns the base token exchange rate for a given position. Defaults to 1 for all staked /// positions created prior to GIP-1 (before the `unsafeBaseTokenExchangeRate` field was added). /// @dev Always use this method to get the base token exchange rate to ensure proper handling of /// old staked positions. function safeBaseTokenExchangeRate(StakedPosition storage position) internal view returns (uint256) { if (position.unsafeBaseTokenExchangeRate > 0) { return position.unsafeBaseTokenExchangeRate; } return MULTIPLIER_DECIMALS; } /// @notice The effective multiplier to use with new staked positions of the provided `positionType`, /// for denominating them in terms of `baseStakingToken()`. This value is denominated in `MULTIPLIER_DECIMALS`. function getEffectiveMultiplierForPositionType(StakedPositionType positionType) public view returns (uint256) { if (effectiveMultipliers[positionType] > 0) { return effectiveMultipliers[positionType]; } return MULTIPLIER_DECIMALS; // 1x } /// @notice Calculate the exchange rate that will be used to convert the original staked token amount to the /// `baseStakingToken()` amount. The exchange rate is denominated in `MULTIPLIER_DECIMALS`. /// @param positionType Type of the staked postion function getBaseTokenExchangeRate(StakedPositionType positionType) public view virtual returns (uint256) { if (positionType == StakedPositionType.CurveLP) { // Curve LP tokens are scaled by MULTIPLIER_DECIMALS (1e18), uint256 curveLPVirtualPrice = config.getFiduUSDCCurveLP().get_virtual_price(); // @dev LOW: The Curve LP token virtual price is too low require(curveLPVirtualPrice > MULTIPLIER_DECIMALS.div(2), "LOW"); // @dev HIGH: The Curve LP token virtual price is too high require(curveLPVirtualPrice < MULTIPLIER_DECIMALS.mul(2), "HIGH"); // The FIDU token price is also scaled by MULTIPLIER_DECIMALS (1e18) return curveLPVirtualPrice.mul(MULTIPLIER_DECIMALS).div(config.getSeniorPool().sharePrice()); } return MULTIPLIER_DECIMALS; // 1x } function _stake( address staker, address nftRecipient, uint256 amount, StakedPositionType positionType ) internal returns (uint256 tokenId) { /// @dev ZERO: Cannot stake 0 require(amount > 0, "ZERO"); _tokenIdTracker.increment(); tokenId = _tokenIdTracker.current(); // Ensure we snapshot accumulatedRewardsPerToken for tokenId after it is available // We do this before setting the position, because we don't want `earned` to (incorrectly) account for // position.amount yet. This is equivalent to using the updateReward(msg.sender) modifier in the original // synthetix contract, where the modifier is called before any staking balance for that address is recorded _updateReward(tokenId); uint256 baseTokenExchangeRate = getBaseTokenExchangeRate(positionType); uint256 effectiveMultiplier = getEffectiveMultiplierForPositionType(positionType); positions[tokenId] = StakedPosition({ positionType: positionType, amount: amount, rewards: StakingRewardsVesting.Rewards({ totalUnvested: 0, totalVested: 0, totalPreviouslyVested: 0, totalClaimed: 0, startTime: block.timestamp, endTime: block.timestamp.add(vestingLength) }), unsafeBaseTokenExchangeRate: baseTokenExchangeRate, unsafeEffectiveMultiplier: effectiveMultiplier, leverageMultiplier: 0, lockedUntil: 0 }); _mint(nftRecipient, tokenId); uint256 effectiveAmount = _positionToEffectiveAmount(positions[tokenId]); totalStakedSupply = totalStakedSupply.add(effectiveAmount); // Staker is address(this) when using depositAndStake or other convenience functions if (staker != address(this)) { stakingToken(positionType).safeTransferFrom(staker, address(this), amount); } emit Staked(nftRecipient, tokenId, amount, positionType, baseTokenExchangeRate); return tokenId; } /// @notice Unstake an amount of `stakingToken()` associated with a given position and transfer to msg.sender. /// Unvested rewards will be forfeited, but remaining staked amount will continue to accrue rewards. /// Positions that are still locked cannot be unstaked until the position's lockedUntil time has passed. /// @dev This function checkpoints rewards /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be unstaked from the position function unstake(uint256 tokenId, uint256 amount) public nonReentrant whenNotPaused updateReward(tokenId) { _unstake(tokenId, amount); stakingToken(positions[tokenId].positionType).safeTransfer(msg.sender, amount); } /// @notice Unstake multiple positions and transfer to msg.sender. /// /// @dev This function checkpoints rewards /// @param tokenIds A list of position token IDs /// @param amounts A list of amounts of `stakingToken()` to be unstaked from the position function unstakeMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == amounts.length, "LEN"); uint256 fiduAmountToUnstake = 0; uint256 curveAmountToUnstake = 0; for (uint256 i = 0; i < amounts.length; i++) { StakedPositionType positionType = positions[tokenIds[i]].positionType; _unstake(tokenIds[i], amounts[i]); if (positionType == StakedPositionType.CurveLP) { curveAmountToUnstake = curveAmountToUnstake.add(amounts[i]); } else { fiduAmountToUnstake = fiduAmountToUnstake.add(amounts[i]); } } if (fiduAmountToUnstake > 0) { stakingToken(StakedPositionType.Fidu).safeTransfer(msg.sender, fiduAmountToUnstake); } if (curveAmountToUnstake > 0) { stakingToken(StakedPositionType.CurveLP).safeTransfer(msg.sender, curveAmountToUnstake); } emit UnstakedMultiple(msg.sender, tokenIds, amounts); } function unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) external nonReentrant whenNotPaused { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenId, usdcAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdraw(uint256 tokenId, uint256 usdcAmount) internal updateReward(tokenId) returns (uint256 usdcAmountReceived, uint256 fiduUsed) { /// @dev CW: Cannot withdraw funds with this position require(canWithdraw(tokenId), "CW"); /// @dev GL: This address has not been go-listed require(isGoListed(), "GL"); IFidu fidu = config.getFidu(); uint256 fiduBalanceBefore = fidu.balanceOf(address(this)); usdcAmountReceived = config.getSeniorPool().withdraw(usdcAmount); fiduUsed = fiduBalanceBefore.sub(fidu.balanceOf(address(this))); _unstake(tokenId, fiduUsed); config.getUSDC().safeTransfer(msg.sender, usdcAmountReceived); return (usdcAmountReceived, fiduUsed); } function unstakeAndWithdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata usdcAmounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == usdcAmounts.length, "LEN"); uint256 usdcReceivedAmountTotal = 0; uint256[] memory fiduAmounts = new uint256[](usdcAmounts.length); for (uint256 i = 0; i < usdcAmounts.length; i++) { (uint256 usdcReceivedAmount, uint256 fiduAmount) = _unstakeAndWithdraw(tokenIds[i], usdcAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); fiduAmounts[i] = fiduAmount; } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) external nonReentrant whenNotPaused { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenId, fiduAmount); emit UnstakedAndWithdrew(msg.sender, usdcReceivedAmount, tokenId, fiduAmount); } function _unstakeAndWithdrawInFidu(uint256 tokenId, uint256 fiduAmount) internal updateReward(tokenId) returns (uint256 usdcReceivedAmount) { /// @dev CW: Cannot withdraw funds with this position require(canWithdraw(tokenId), "CW"); usdcReceivedAmount = config.getSeniorPool().withdrawInFidu(fiduAmount); _unstake(tokenId, fiduAmount); config.getUSDC().safeTransfer(msg.sender, usdcReceivedAmount); return usdcReceivedAmount; } function unstakeAndWithdrawMultipleInFidu(uint256[] calldata tokenIds, uint256[] calldata fiduAmounts) external nonReentrant whenNotPaused { /// @dev LEN: Params must have the same length require(tokenIds.length == fiduAmounts.length, "LEN"); uint256 usdcReceivedAmountTotal = 0; for (uint256 i = 0; i < fiduAmounts.length; i++) { uint256 usdcReceivedAmount = _unstakeAndWithdrawInFidu(tokenIds[i], fiduAmounts[i]); usdcReceivedAmountTotal = usdcReceivedAmountTotal.add(usdcReceivedAmount); } emit UnstakedAndWithdrewMultiple(msg.sender, usdcReceivedAmountTotal, tokenIds, fiduAmounts); } function _unstake(uint256 tokenId, uint256 amount) internal { /// @dev AD: Access denied require(_isApprovedOrOwner(msg.sender, tokenId), "AD"); StakedPosition storage position = positions[tokenId]; uint256 prevAmount = position.amount; /// @dev IA: Invalid amount. Cannot unstake zero, and cannot unstake more than staked balance. require(amount > 0 && amount <= prevAmount, "IA"); /// @dev LOCKED: Staked funds are locked. require(block.timestamp >= position.lockedUntil, "LOCKED"); uint256 effectiveAmount = toEffectiveAmount( amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position) ); totalStakedSupply = totalStakedSupply.sub(effectiveAmount); position.amount = prevAmount.sub(amount); // Slash unvested rewards. If this method is being called by the Zapper, then unvested rewards are not slashed. // This exception is made so that users who wish to move their funds across the protocol are not penalized for // doing so. // See https://gov.goldfinch.finance/t/gip-03-no-cost-forfeit-to-swap-fidu-into-backer-nfts/784 if (!isZapper()) { uint256 slashingPercentage = amount.mul(StakingRewardsVesting.PERCENTAGE_DECIMALS).div(prevAmount); position.rewards.slash(slashingPercentage); } emit Unstaked(msg.sender, tokenId, amount, position.positionType); } /// @notice "Kick" a user's reward multiplier. If they are past their lock-up period, their reward /// multiplier will be reset to 1x. /// @dev This will also checkpoint their rewards up to the current time. // solhint-disable-next-line no-empty-blocks function kick(uint256 tokenId) external nonReentrant whenNotPaused updateReward(tokenId) {} /// @notice Updates a user's effective multiplier to the prevailing multiplier. This function gives /// users an option to get on a higher multiplier without needing to unstake and lose their unvested tokens. /// @dev This will also checkpoint their rewards up to the current time. function updatePositionEffectiveMultiplier(uint256 tokenId) external nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(ownerOf(tokenId) == msg.sender, "AD"); StakedPosition storage position = positions[tokenId]; uint256 newEffectiveMultiplier = getEffectiveMultiplierForPositionType(position.positionType); /// We want to honor the original multiplier for the user's sake, so we don't want to /// allow the effective multiplier for a given position to decrease. /// @dev LOW: Cannot update position to a lower effective multiplier require(newEffectiveMultiplier >= safeEffectiveMultiplier(position), "LOW"); uint256 prevEffectiveAmount = _positionToEffectiveAmount(position); position.unsafeEffectiveMultiplier = newEffectiveMultiplier; uint256 newEffectiveAmount = _positionToEffectiveAmount(position); totalStakedSupply = totalStakedSupply.sub(prevEffectiveAmount).add(newEffectiveAmount); } /// @notice Claim rewards for a given staked position /// @param tokenId A staking position token ID function getReward(uint256 tokenId) public nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(ownerOf(tokenId) == msg.sender, "AD"); uint256 reward = claimableRewards(tokenId); if (reward > 0) { positions[tokenId].rewards.claim(reward); rewardsToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, tokenId, reward); } } /// @notice Add to an existing position without affecting vesting schedule /// @dev This function checkpoints rewards and is only callable by an approved address with ZAPPER_ROLE. This /// function enables the Zapper to unwind "in-progress" positions initiated by `Zapper.zapStakeToTranchedPool`. /// That is, funds that were moved from this contract into a TranchedPool can be "unwound" back to their original /// staked position by the Zapper as part of `Zapper.unzapToStakingRewards`. /// @param tokenId A staking position token ID /// @param amount Amount of `stakingToken()` to be added to tokenId's position function addToStake(uint256 tokenId, uint256 amount) external nonReentrant whenNotPaused updateReward(tokenId) { /// @dev AD: Access denied require(isZapper() && _isApprovedOrOwner(msg.sender, tokenId), "AD"); /// @dev PT: Position type is incorrect for this action require(positions[tokenId].positionType == StakedPositionType.Fidu, "PT"); StakedPosition storage position = positions[tokenId]; position.amount = position.amount.add(amount); uint256 effectiveAmount = toEffectiveAmount( amount, safeBaseTokenExchangeRate(position), safeEffectiveMultiplier(position) ); totalStakedSupply = totalStakedSupply.add(effectiveAmount); stakingToken(position.positionType).safeTransferFrom(msg.sender, address(this), amount); } /* ========== RESTRICTED FUNCTIONS ========== */ /// @notice Transfer rewards from msg.sender, to be used for reward distribution function loadRewards(uint256 rewards) external onlyAdmin updateReward(0) { rewardsToken().safeTransferFrom(msg.sender, address(this), rewards); rewardsAvailable = rewardsAvailable.add(rewards); emit RewardAdded(rewards); } function setRewardsParameters( uint256 _targetCapacity, uint256 _minRate, uint256 _maxRate, uint256 _minRateAtPercent, uint256 _maxRateAtPercent ) external onlyAdmin updateReward(0) { /// @dev IP: Invalid parameters. maxRate must be >= then minRate. maxRateAtPercent must be <= minRateAtPercent. require(_maxRate >= _minRate && _maxRateAtPercent <= _minRateAtPercent, "IP"); targetCapacity = _targetCapacity; minRate = _minRate; maxRate = _maxRate; minRateAtPercent = _minRateAtPercent; maxRateAtPercent = _maxRateAtPercent; emit RewardsParametersUpdated(msg.sender, targetCapacity, minRate, maxRate, minRateAtPercent, maxRateAtPercent); } /// @notice Set the effective multiplier for a given staked position type. The effective multipler /// is used to denominate a staked position to `baseStakingToken()`. The multiplier is represented in /// `MULTIPLIER_DECIMALS` /// @param multiplier the new multiplier, denominated in `MULTIPLIER_DECIMALS` /// @param positionType the type of the position function setEffectiveMultiplier(uint256 multiplier, StakedPositionType positionType) external onlyAdmin updateReward(0) { // @dev ZERO: Multiplier cannot be zero require(multiplier > 0, "ZERO"); effectiveMultipliers[positionType] = multiplier; emit EffectiveMultiplierUpdated(_msgSender(), positionType, multiplier); } function setVestingSchedule(uint256 _vestingLength) external onlyAdmin updateReward(0) { vestingLength = _vestingLength; emit VestingScheduleUpdated(msg.sender, vestingLength); } /* ========== MODIFIERS ========== */ modifier updateReward(uint256 tokenId) { _updateReward(tokenId); _; } function _updateReward(uint256 tokenId) internal { uint256 prevAccumulatedRewardsPerToken = accumulatedRewardsPerToken; accumulatedRewardsPerToken = rewardPerToken(); uint256 rewardsJustDistributed = totalStakedSupply .mul(accumulatedRewardsPerToken.sub(prevAccumulatedRewardsPerToken)) .div(stakingAndRewardsTokenMantissa()); rewardsAvailable = rewardsAvailable.sub(rewardsJustDistributed); lastUpdateTime = block.timestamp; if (tokenId != 0) { uint256 additionalRewards = earnedSinceLastCheckpoint(tokenId); StakingRewardsVesting.Rewards storage rewards = positions[tokenId].rewards; rewards.totalUnvested = rewards.totalUnvested.add(additionalRewards); rewards.checkpoint(); positionToAccumulatedRewardsPerToken[tokenId] = accumulatedRewardsPerToken; } } function isAdmin() internal view returns (bool) { return hasRole(OWNER_ROLE, _msgSender()); } modifier onlyAdmin() { /// @dev AD: Must have admin role to perform this action require(isAdmin(), "AD"); _; } function isZapper() internal view returns (bool) { return hasRole(ZAPPER_ROLE, _msgSender()); } function isGoListed() internal view returns (bool) { return config.getGo().goSeniorPool(msg.sender); } function canWithdraw(uint256 tokenId) internal view returns (bool) { return positions[tokenId].positionType == StakedPositionType.Fidu; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked( address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType, uint256 baseTokenExchangeRate ); event DepositedAndStaked(address indexed user, uint256 depositedAmount, uint256 indexed tokenId, uint256 amount); event DepositedToCurve(address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 tokensReceived); event DepositedToCurveAndStaked( address indexed user, uint256 fiduAmount, uint256 usdcAmount, uint256 indexed tokenId, uint256 amount ); event Unstaked(address indexed user, uint256 indexed tokenId, uint256 amount, StakedPositionType positionType); event UnstakedMultiple(address indexed user, uint256[] tokenIds, uint256[] amounts); event UnstakedAndWithdrew(address indexed user, uint256 usdcReceivedAmount, uint256 indexed tokenId, uint256 amount); event UnstakedAndWithdrewMultiple( address indexed user, uint256 usdcReceivedAmount, uint256[] tokenIds, uint256[] amounts ); event RewardPaid(address indexed user, uint256 indexed tokenId, uint256 reward); event GoldfinchConfigUpdated(address indexed who, address configAddress); }
@notice The address of the base token used to denominate staking rewards
function baseStakingToken() internal view returns (IERC20withDec) { return config.getFidu(); }
13,058,084
[ 1, 1986, 1758, 434, 326, 1026, 1147, 1399, 358, 10716, 3322, 384, 6159, 283, 6397, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1026, 510, 6159, 1345, 1435, 2713, 1476, 1135, 261, 45, 654, 39, 3462, 1918, 1799, 13, 288, 203, 565, 327, 642, 18, 588, 42, 350, 89, 5621, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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-or-later pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import '@uniswap/lib/contracts/libraries/TransferHelper.sol'; import "../lib/access/OwnableUpgradeable.sol"; import "../lib/util/MathUtil.sol"; /** * @title NYM * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract NymUpgradeable is OwnableUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using StringsUpgradeable for uint256; uint256 private _currentTokenId; // Capacity of token uint256 private _cap; uint256 public totalSupply; // Price to mint a token uint256 public mintPrice; // 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Mapping from token ID to owner address mapping (uint256 => address) 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; uint256[] private _freeTokenIds; bool public locked; // Events event NewNym (address indexed to, uint256 indexed tokenId, uint256 mintPrice); event NewCapacity (uint256 indexed newCapacity); event NewMintPrice (uint256 indexed newMintPrice); event NewLocked (bool indexed newLocked); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function initialize( address ownerAddress_, string memory baseURI_ ) public initializer { require(ownerAddress_ != address(0), "Invalid owner"); _name = "NEONPUNK"; _symbol = "NEON"; _cap = 300; mintPrice = 15e16; // 0.15 ETH locked = true; __Ownable_init(ownerAddress_); __ERC165_init(); // register the supported interfaces to conform to ERC721 via ERC165Upgradeable _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _baseURI = baseURI_; _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x9A72088c3D45Da0b874CF42eDF285B0600B36FCc); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x9A72088c3D45Da0b874CF42eDF285B0600B36FCc); _mintInternal(0xab0B18523e8fe8CBF947C55632e8aB5Ce936ae8c); _mintInternal(0x32a51d0Ad4Ff0876E94858970688FE80B80EAD6e); _mintInternal(0x6BD58Fccf92631d168A4635814eF6a1d8B9aaba7); _mintInternal(0xda59E40c7BD1d961D4c54c0AD55Ac13C4927b73a); for (uint id = _currentTokenId+1; id <= _cap; id ++) { _freeTokenIds.push(id); } } /** * @dev Returns the cap on the token's total supply. */ function capacity() external view returns (uint256) { return _cap; } /** * @dev Set the cap. */ function setCapacity(uint256 cap) onlyOwner external { require(totalSupply <= cap, "capacity is less than the current supply"); _cap = cap; emit NewCapacity(_cap); } /** * @dev Set the minting price. */ function setMintPrice(uint256 price) onlyOwner external { mintPrice = price; emit NewMintPrice(mintPrice); } /** * @dev Set the 'locked' flag. */ function setLocked(bool _locked) onlyOwner external { locked = _locked; emit NewLocked(locked); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address tokenOwner) public view override returns (uint256) { require(tokenOwner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[tokenOwner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address owner_) { owner_ = _tokenOwners[tokenId]; require(owner_ != address(0) , "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view 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 tokenOwner, uint256 index) public view returns (uint256) { return _holderTokens[tokenOwner].at(index); } /** * @dev Mints a NYM */ function mint(uint256 qty) external payable { require(0 < qty, "Quantity is zero"); require(totalSupply.add(qty) <= _cap, "Exceeds capacity"); require(mintPrice.mul(qty) == msg.value, "Ether value sent is not correct"); address sender = _msgSender(); for (uint i = 0; i < qty; i ++) { _mintInternal(sender); } } function _mintInternal(address to) internal { uint256 tokenId; uint256 count = _freeTokenIds.length; if (0 < count) { uint index = MathUtil.random() % count; tokenId = _freeTokenIds[index]; _freeTokenIds[index] = _freeTokenIds[count-1]; _freeTokenIds.pop(); } else { tokenId = ++ _currentTokenId; } _safeMint(to, tokenId, ""); emit NewNym(to, tokenId, mintPrice); } /** * @dev Withdraw ether from this contract (Callable by owner) */ function withdraw() onlyOwner external { uint balance = address(this).balance; TransferHelper.safeTransferETH(owner(), balance); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address tokenOwner = ownerOf(tokenId); require(to != tokenOwner, "ERC721: approval to current token owner"); require(_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()), "ERC721: approve caller is not token owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view 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 tokenOwner, address operator) public view override returns (bool) { return _operatorApprovals[tokenOwner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) external virtual override { _safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) external virtual override { _safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external virtual override { _safeTransferFrom(from, to, tokenId, _data); } function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not token 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 returns (bool) { return (_tokenOwners[tokenId] != address(0)); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address tokenOwner = ownerOf(tokenId); return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, 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[tokenId] = to; totalSupply ++; 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 tokenOwner = ownerOf(tokenId); _beforeTokenTransfer(tokenOwner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[tokenOwner].remove(tokenId); _tokenOwners[tokenId] = address(0); totalSupply --; emit Transfer(tokenOwner, 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(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); require(!locked, "No transfer allowed yet"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous token owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners[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) onlyOwner external { 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_) onlyOwner external { _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( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 { } function freeCount() public view returns(uint256) { return _freeTokenIds.length; } } contract NymUpgradeableProxy is TransparentUpgradeableProxy { constructor(address logic, address admin, bytes memory data) TransparentUpgradeableProxy(logic, admin, data) public { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external virtual ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable virtual ifAdmin { _upgradeTo(newImplementation); Address.functionDelegateCall(newImplementation, data); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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; } uint256[49] private __gap; } // 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.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.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; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init(address _ownerAddress) internal initializer { __Context_init_unchained(); __Ownable_init_unchained(_ownerAddress); } function __Ownable_init_unchained(address _ownerAddress) internal initializer { _owner = _ownerAddress; emit OwnershipTransferred(address(0), _ownerAddress); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @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 safeTransferOwnership(address newOwner, bool safely) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); if (safely) { _pendingOwner = newOwner; } else { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; _pendingOwner = address(0); } } function safeAcceptOwnership() public virtual { require(_msgSender() == _pendingOwner, "acceptOwnership: Call must come from pendingOwner."); emit OwnershipTransferred(_owner, _pendingOwner); _owner = _pendingOwner; } uint256[48] private __gap; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.7.6; library MathUtil { // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } function random() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { Address.functionDelegateCall(_logic, _data); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal virtual { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // 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 "../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; }
implementation from https:github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 original implementation: https:github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
library MathUtil { pragma solidity 0.7.6; function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return (r < r1 ? r : r1); } function random() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty))); } }
1,172,771
[ 1, 30810, 628, 2333, 30, 6662, 18, 832, 19, 984, 291, 91, 438, 19, 318, 291, 91, 438, 17, 2941, 19, 7371, 19, 2733, 74, 23, 74, 6030, 4700, 20, 1105, 20, 12124, 21, 9897, 21, 1403, 24, 4848, 1077, 27, 71, 25, 5540, 22, 19192, 28, 5540, 21, 69, 20, 2282, 4471, 30, 2333, 30, 6662, 18, 832, 19, 378, 2883, 17, 8559, 406, 310, 19, 378, 2883, 17, 31417, 17, 30205, 560, 19, 10721, 19, 7525, 19, 2090, 3398, 10477, 1105, 92, 1105, 18, 18281, 48, 9470, 27, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2361, 1304, 288, 203, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 26, 31, 203, 565, 445, 5700, 12, 11890, 5034, 619, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 92, 422, 374, 13, 327, 374, 31, 203, 3639, 2254, 5034, 12223, 273, 619, 31, 203, 3639, 2254, 5034, 436, 273, 404, 31, 203, 203, 3639, 309, 261, 5279, 1545, 374, 92, 21, 12648, 12648, 12648, 12648, 13, 288, 203, 5411, 12223, 23359, 8038, 31, 203, 5411, 436, 22789, 5178, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 21, 12648, 12648, 13, 288, 203, 5411, 12223, 23359, 5178, 31, 203, 5411, 436, 22789, 3847, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 21, 12648, 13, 288, 203, 5411, 12223, 23359, 3847, 31, 203, 5411, 436, 22789, 2872, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 23899, 13, 288, 203, 5411, 12223, 23359, 2872, 31, 203, 5411, 436, 22789, 1725, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 6625, 13, 288, 203, 5411, 12223, 23359, 1725, 31, 203, 5411, 436, 22789, 1059, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 2163, 13, 288, 203, 5411, 12223, 23359, 1059, 31, 203, 5411, 436, 22789, 576, 31, 203, 3639, 289, 203, 3639, 309, 261, 5279, 1545, 374, 92, 28, 13, 288, 203, 5411, 436, 22789, 404, 31, 203, 3639, 289, 203, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 2 ]
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; /** * SafeMath from OpenZeppelin - commit https://github.com/OpenZeppelin/openzeppelin-contracts/commit/5dfe7215a9156465d550030eadc08770503b2b2f * * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @title MBDAAsset is a template for MB Digital Asset token * */ contract MBDAAsset { using SafeMath for uint256; // // events // // ERC20 events event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); // mint/burn events event Mint(address indexed _to, uint256 _amount, uint256 _newTotalSupply); event Burn(address indexed _from, uint256 _amount, uint256 _newTotalSupply); // admin events event BlockLockSet(uint256 _value); event NewAdmin(address _newAdmin); event NewManager(address _newManager); event NewInvestor(address _newInvestor); event RemovedInvestor(address _investor); event FundAssetsChanged( string indexed tokenSymbol, string assetInfo, uint8 amount, uint256 totalAssetAmount ); modifier onlyAdmin { require(msg.sender == admin, "Only admin can perform this operation"); _; } modifier managerOrAdmin { require( msg.sender == manager || msg.sender == admin, "Only manager or admin can perform this operation" ); _; } modifier boardOrAdmin { require( msg.sender == board || msg.sender == admin, "Only admin or board can perform this operation" ); _; } modifier blockLock(address _sender) { require( !isLocked() || _sender == admin, "Contract is locked except for the admin" ); _; } modifier onlyIfMintable() { require(mintable, "Token minting is disabled"); _; } struct Asset { string assetTicker; string assetInfo; uint8 assetPercentageParticipation; } struct Investor { string info; bool exists; } uint256 public totalSupply; string public name; uint8 public decimals; string public symbol; address public admin; address public board; address public manager; uint256 public lockedUntilBlock; bool public canChangeAssets; bool public mintable; bool public hasWhiteList; bool public isSyndicate; string public urlFinancialDetailsDocument; bytes32 public financialDetailsHash; string[] public tradingPlatforms; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; mapping(address => Investor) public clearedInvestors; Asset[] public assets; /** * @dev Constructor * @param _fundAdmin - Fund admin * @param _fundBoard - Board * @param _tokenName - Detailed ERC20 token name * @param _decimalUnits - Detailed ERC20 decimal units * @param _tokenSymbol - Detailed ERC20 token symbol * @param _lockedUntilBlock - Block lock * @param _newTotalSupply - Total Supply owned by the contract itself, only Manager can move * @param _canChangeAssets - True allows the Manager to change assets in the portfolio * @param _mintable - True allows Manager to rebalance the portfolio * @param _hasWhiteList - Allows transfering only between whitelisted addresses * @param _isSyndicate - Allows secondary market */ constructor( address _fundAdmin, address _fundBoard, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, uint256 _lockedUntilBlock, uint256 _newTotalSupply, bool _canChangeAssets, bool _mintable, bool _hasWhiteList, bool _isSyndicate ) public { name = _tokenName; require(_decimalUnits <= 18, "Decimal units should be 18 or lower"); decimals = _decimalUnits; symbol = _tokenSymbol; lockedUntilBlock = _lockedUntilBlock; admin = _fundAdmin; board = _fundBoard; totalSupply = _newTotalSupply; canChangeAssets = _canChangeAssets; mintable = _mintable; hasWhiteList = _hasWhiteList; isSyndicate = _isSyndicate; balances[address(this)] = totalSupply; Investor memory tmp = Investor("Contract", true); clearedInvestors[address(this)] = tmp; emit NewInvestor(address(this)); } /** * @dev Set financial details url * @param _url - URL * @return True if success */ function setFinancialDetails(string memory _url) public onlyAdmin returns (bool) { urlFinancialDetailsDocument = _url; return true; } /** * @dev Set financial details IPFS hash * @param _hash - URL * @return True if success */ function setFinancialDetailsHash(bytes32 _hash) public onlyAdmin returns (bool) { financialDetailsHash = _hash; return true; } /** * @dev Add trading platform * @param _details - Details of the trading platform * @return True if success */ function addTradingPlatform(string memory _details) public onlyAdmin returns (bool) { tradingPlatforms.push(_details); return true; } /** * @dev Remove trading platform * @param _index - Index of the trading platform to be removed * @return True if success */ function removeTradingPlatform(uint256 _index) public onlyAdmin returns (bool) { require(_index < tradingPlatforms.length, "Invalid platform index"); tradingPlatforms[_index] = tradingPlatforms[tradingPlatforms.length - 1]; tradingPlatforms.pop(); return true; } /** * @dev Whitelists an Investor * @param _investor - Address of the investor * @param _investorInfo - Info * @return True if success */ function addNewInvestor(address _investor, string memory _investorInfo) public onlyAdmin returns (bool) { require(_investor != address(0), "Invalid investor address"); Investor memory tmp = Investor(_investorInfo, true); clearedInvestors[_investor] = tmp; emit NewInvestor(_investor); return true; } /** * @dev Removes an Investor from whitelist * @param _investor - Address of the investor * @return True if success */ function removeInvestor(address _investor) public onlyAdmin returns (bool) { require(_investor != address(0), "Invalid investor address"); delete (clearedInvestors[_investor]); emit RemovedInvestor(_investor); return true; } /** * @dev Add new asset to Portfolio * @param _assetTicker - Ticker * @param _assetInfo - Info * @param _assetPercentageParticipation - % of portfolio taken by the asset * @return success */ function addNewAsset( string memory _assetTicker, string memory _assetInfo, uint8 _assetPercentageParticipation ) public onlyAdmin returns (bool success) { uint256 totalPercentageAssets = 0; for (uint256 i = 0; i < assets.length; i++) { require( keccak256(bytes(_assetTicker)) != keccak256(bytes(assets[i].assetTicker)), "An asset cannot be assigned twice" ); totalPercentageAssets = SafeMath.add( assets[i].assetPercentageParticipation, totalPercentageAssets ); } totalPercentageAssets = SafeMath.add( totalPercentageAssets, _assetPercentageParticipation ); require( totalPercentageAssets <= 100, "Total assets number cannot be higher than 100" ); emit FundAssetsChanged( _assetTicker, _assetInfo, _assetPercentageParticipation, totalPercentageAssets ); Asset memory newAsset = Asset( _assetTicker, _assetInfo, _assetPercentageParticipation ); assets.push(newAsset); success = true; return success; } /** * @dev Remove asset from Portfolio * @param _assetIndex - Asset * @return True if success */ function removeAnAsset(uint8 _assetIndex) public onlyAdmin returns (bool) { require(canChangeAssets, "Cannot change asset portfolio"); require( _assetIndex < assets.length, "Invalid asset index number. Greater than total assets" ); string memory assetTicker = assets[_assetIndex].assetTicker; assets[_assetIndex] = assets[assets.length - 1]; delete assets[assets.length - 1]; assets.pop(); emit FundAssetsChanged(assetTicker, "", 0, 0); return true; } /** * @dev Updates an asset * @param _assetTicker - Ticker * @param _assetInfo - Info to update * @param _newAmount - % of portfolio taken by the asset * @return True if success */ function updateAnAssetQuantity( string memory _assetTicker, string memory _assetInfo, uint8 _newAmount ) public onlyAdmin returns (bool) { require(canChangeAssets, "Cannot change asset amount"); require(_newAmount > 0, "Cannot set zero asset amount"); uint256 totalAssets = 0; uint256 assetIndex = 0; for (uint256 i = 0; i < assets.length; i++) { if ( keccak256(bytes(_assetTicker)) == keccak256(bytes(assets[i].assetTicker)) ) { assetIndex = i; totalAssets = SafeMath.add(totalAssets, _newAmount); } else { totalAssets = SafeMath.add( totalAssets, assets[i].assetPercentageParticipation ); } } emit FundAssetsChanged( _assetTicker, _assetInfo, _newAmount, totalAssets ); require( totalAssets <= 100, "Fund assets total percentage must be less than 100" ); assets[assetIndex].assetPercentageParticipation = _newAmount; assets[assetIndex].assetInfo = _assetInfo; return true; } /** * @return Number of assets in Portfolio */ function totalAssetsArray() public view returns (uint256) { return assets.length; } /** * @dev ERC20 Transfer * @param _to - destination address * @param _value - value to transfer * @return True if success */ function transfer(address _to, uint256 _value) public blockLock(msg.sender) returns (bool) { address from = (admin == msg.sender) ? address(this) : msg.sender; require( isTransferValid(from, _to, _value), "Invalid Transfer Operation" ); balances[from] = balances[from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(from, _to, _value); return true; } /** * @dev ERC20 Approve * @param _spender - destination address * @param _value - value to be approved * @return True if success */ function approve(address _spender, uint256 _value) public blockLock(msg.sender) returns (bool) { require(_spender != address(0), "ERC20: approve to the zero address"); address from = (admin == msg.sender) ? address(this) : msg.sender; allowed[from][_spender] = _value; emit Approval(from, _spender, _value); return true; } /** * @dev ERC20 TransferFrom * @param _from - source address * @param _to - destination address * @param _value - value * @return True if success */ function transferFrom(address _from, address _to, uint256 _value) public blockLock(_from) returns (bool) { // check sufficient allowance require( _value <= allowed[_from][msg.sender], "Value informed is invalid" ); require( isTransferValid(_from, _to, _value), "Invalid Transfer Operation" ); // transfer tokens balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub( _value, "Value lower than approval" ); emit Transfer(_from, _to, _value); return true; } /** * @dev Mint new tokens. Can only be called by minter or owner * @param _to - destination address * @param _value - value * @return True if success */ function mint(address _to, uint256 _value) public onlyIfMintable managerOrAdmin blockLock(msg.sender) returns (bool) { balances[_to] = balances[_to].add(_value); totalSupply = totalSupply.add(_value); emit Mint(_to, _value, totalSupply); emit Transfer(address(0), _to, _value); return true; } /** * @dev Burn tokens * @param _account - address * @param _value - value * @return True if success */ function burn(address payable _account, uint256 _value) public payable blockLock(msg.sender) managerOrAdmin returns (bool) { require(_account != address(0), "ERC20: burn from the zero address"); totalSupply = totalSupply.sub(_value); balances[_account] = balances[_account].sub(_value); emit Transfer(_account, address(0), _value); emit Burn(_account, _value, totalSupply); if (msg.value > 0) { (bool success, ) = _account.call{value: msg.value}(""); require(success, "Ether transfer failed."); } return true; } /** * @dev Set block lock. Until that block (exclusive) transfers are disallowed * @param _lockedUntilBlock - Block Number * @return True if success */ function setBlockLock(uint256 _lockedUntilBlock) public boardOrAdmin returns (bool) { lockedUntilBlock = _lockedUntilBlock; emit BlockLockSet(_lockedUntilBlock); return true; } /** * @dev Replace current admin with new one * @param _newAdmin New token admin * @return True if success */ function replaceAdmin(address _newAdmin) public boardOrAdmin returns (bool) { require(_newAdmin != address(0x0), "Null address"); admin = _newAdmin; emit NewAdmin(_newAdmin); return true; } /** * @dev Set an account can perform some operations * @param _newManager Manager address * @return True if success */ function setManager(address _newManager) public onlyAdmin returns (bool) { manager = _newManager; emit NewManager(_newManager); return true; } /** * @dev ERC20 balanceOf * @param _owner Owner address * @return True if success */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev ERC20 allowance * @param _owner Owner address * @param _spender Address allowed to spend from Owner's balance * @return uint256 allowance */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Are transfers currently disallowed * @return True if disallowed */ function isLocked() public view returns (bool) { return lockedUntilBlock > block.number; } /** * @dev Checks if transfer parameters are valid * @param _from Source address * @param _to Destination address * @param _amount Amount to check * @return True if valid */ function isTransferValid(address _from, address _to, uint256 _amount) public view returns (bool) { if (_from == address(0)) { return false; } if (_to == address(0)) { return false; } if (!hasWhiteList) { return balances[_from] >= _amount; // sufficient balance } bool fromOK = clearedInvestors[_from].exists; if (!isSyndicate) { return balances[_from] >= _amount && // sufficient balance fromOK; // a seller holder within the whitelist } bool toOK = clearedInvestors[_to].exists; return balances[_from] >= _amount && // sufficient balance fromOK && // a seller holder within the whitelist toOK; // a buyer holder within the whitelist } } contract MBDAWallet { mapping(address => bool) public controllers; address[] public controllerList; bytes32 public recipientID; string public recipient; modifier onlyController() { require(controllers[msg.sender], "Sender must be a Controller Member"); _; } event EtherReceived(address sender, uint256 amount); /** * @dev Constructor * @param _controller - Controller of the new wallet * @param recipientExternalID - The Recipient ID (managed externally) */ constructor(address _controller, string memory recipientExternalID) public { require(_controller != address(0), "Invalid address of controller 1"); controllers[_controller] = true; controllerList.push(_controller); recipientID = keccak256(abi.encodePacked(recipientExternalID)); recipient = recipientExternalID; } /** * @dev Getter for the total number of controllers * @return Total number of controllers */ function getTotalControllers() public view returns (uint256) { return controllerList.length; } /** * @dev Adds a new Controller * @param _controller - Controller to be added * @return True if success */ function newController(address _controller) public onlyController returns (bool) { require(!controllers[_controller], "Already a controller"); require(_controller != address(0), "Invalid Controller address"); require( msg.sender != _controller, "The sender cannot vote to include himself" ); controllers[_controller] = true; controllerList.push(_controller); return true; } /** * @dev Deletes a Controller * @param _controller - Controller to be deleted * @return True if success */ function deleteController(address _controller) public onlyController returns (bool) { require(_controller != address(0), "Invalid Controller address"); require( controllerList.length > 1, "Cannot leave the wallet without a controller" ); delete (controllers[_controller]); for (uint256 i = 0; i < controllerList.length; i++) { if (controllerList[i] == _controller) { controllerList[i] = controllerList[controllerList.length - 1]; delete controllerList[controllerList.length - 1]; controllerList.pop(); return true; } } return false; } /** * @dev Getter for the wallet balance for a given asset * @param _assetAddress - Asset to check balance * @return Balance */ function getBalance(address _assetAddress) public view returns (uint256) { MBDAAsset mbda2 = MBDAAsset(_assetAddress); return mbda2.balanceOf(address(this)); } /** * @dev Transfer and ERC20 asset * @param _assetAddress - Asset * @param _recipient - Recipient * @param _amount - Amount to be transferred * @notice USE NATIVE TOKEN DECIMAL PLACES * @return True if success */ function transfer( address _assetAddress, address _recipient, uint256 _amount ) public onlyController returns (bool) { require(_recipient != address(0), "Invalid address"); MBDAAsset mbda = MBDAAsset(_assetAddress); require( mbda.balanceOf(address(this)) >= _amount, "Insufficient balance" ); return mbda.transfer(_recipient, _amount); } /** * @dev Getter for the Recipient * @return Recipient (string converted) */ function getRecipient() public view returns (string memory) { return recipient; } /** * @dev Getter for the Recipient ID * @return Recipient (bytes32) */ function getRecipientID() external view returns (bytes32) { return recipientID; } /** * @dev Change the recipient of the wallet * @param recipientExternalID - Recipient ID * @return True if success */ function changeRecipient(string memory recipientExternalID) public onlyController returns (bool) { recipientID = keccak256(abi.encodePacked(recipientExternalID)); recipient = recipientExternalID; return true; } /** * @dev Receive * Emits an event on ether received */ receive() external payable { emit EtherReceived(msg.sender, msg.value); } /** * @dev Withdraw Ether from the contract * @param _beneficiary - Destination * @param _amount - Amount * @return True if success */ function withdrawEther(address payable _beneficiary, uint256 _amount) public onlyController returns (bool) { require( address(this).balance >= _amount, "There is not enough balance" ); (bool success, ) = _beneficiary.call{value: _amount}(""); require(success, "Transfer failed."); return success; } function isController(address _checkAddress) external view returns (bool) { return controllers[_checkAddress]; } } /** * @dev Wallet Factory */ contract MBDAWalletFactory { struct Wallet { string recipientID; address walletAddress; address controller; } Wallet[] public wallets; mapping(string => Wallet) public walletsIDMap; event NewWalletCreated( address walletAddress, address indexed controller, string recipientExternalID ); /** * @dev Creates a new wallet * @param _controller - Controller of the new wallet * @param recipientExternalID - The Recipient ID (managed externally) * @return true if success */ function CreateWallet( address _controller, string memory recipientExternalID ) public returns (bool) { Wallet storage wallet = walletsIDMap[recipientExternalID]; require(wallet.walletAddress == address(0x0), "WalletFactory: cannot associate same recipientExternalID twice."); MBDAWallet newWallet = new MBDAWallet( _controller, recipientExternalID ); wallet.walletAddress = address(newWallet); wallet.controller = _controller; wallet.recipientID = recipientExternalID; wallets.push(wallet); walletsIDMap[recipientExternalID] = wallet; emit NewWalletCreated( address(newWallet), _controller, recipientExternalID ); return true; } /** * @dev Total Wallets ever created * @return the total wallets ever created */ function getTotalWalletsCreated() public view returns (uint256) { return wallets.length; } /** * @dev Wallet getter * @param recipientID recipient ID * @return Wallet (for frontend use) */ function getWallet(string calldata recipientID) external view returns (Wallet memory) { require( walletsIDMap[recipientID].walletAddress != address(0x0), "invalid wallet" ); return walletsIDMap[recipientID]; } } /** * @title MBDAManager is a contract that generates tokens that represents a investment fund units and manages them */ contract MBDAManager { struct FundTokenContract { address fundManager; address fundContractAddress; string fundTokenSymbol; bool exists; } FundTokenContract[] public contracts; mapping(address => FundTokenContract) public contractsMap; event NewFundCreated( address indexed fundManager, address indexed tokenAddress, string indexed tokenSymbol ); /** * @dev Creates a new fund token * @param _fundManager - Manager * @param _fundChairman - Chairman * @param _tokenName - Detailed ERC20 token name * @param _decimalUnits - Detailed ERC20 decimal units * @param _tokenSymbol - Detailed ERC20 token symbol * @param _lockedUntilBlock - Block lock * @param _newTotalSupply - Total Supply owned by the contract itself, only Manager can move * @param _canChangeAssets - True allows the Manager to change assets in the portfolio * @param _mintable - True allows Manager to min new tokens * @param _hasWhiteList - Allows transfering only between whitelisted addresses * @param _isSyndicate - Allows secondary market * @return newFundTokenAddress the address of the newly created token */ function newFund( address _fundManager, address _fundChairman, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, uint256 _lockedUntilBlock, uint256 _newTotalSupply, bool _canChangeAssets, // ---> Deixar tudo _canChangeAssets bool _mintable, // ---> Usar aqui _canMintNewTokens bool _hasWhiteList, bool _isSyndicate ) public returns (address newFundTokenAddress) { MBDAAsset ft = new MBDAAsset( _fundManager, _fundChairman, _tokenName, _decimalUnits, _tokenSymbol, _lockedUntilBlock, _newTotalSupply, _canChangeAssets, _mintable, _hasWhiteList, _isSyndicate ); newFundTokenAddress = address(ft); FundTokenContract memory ftc = FundTokenContract( _fundManager, newFundTokenAddress, _tokenSymbol, true ); contracts.push(ftc); contractsMap[ftc.fundContractAddress] = ftc; emit NewFundCreated(_fundManager, newFundTokenAddress, _tokenSymbol); return newFundTokenAddress; } /** * @return Total number of funds created */ function totalContractsGenerated() public view returns (uint256) { return contracts.length; } } /** * @title MbdaBoard is the smart contract that will control all funds * */ contract MbdaBoard { uint256 public minVotes; //minimum number of votes to execute a proposal mapping(address => bool) public boardMembers; //board members address[] public boardMembersList; // array with member addresses /// @dev types of proposal allowed they are Solidity function signatures (bytes4) default ones are added on deploy later more can be added through a proposal mapping(string => bytes4) public proposalTypes; uint256 public totalProposals; /// @notice proposal Struct struct Proposal { string proposalType; address payable destination; uint256 value; uint8 votes; bool executed; bool exists; bytes proposal; /// @dev ABI encoded parameters for the function of the proposal type bool success; bytes returnData; mapping(address => bool) voters; } mapping(uint256 => Proposal) public proposals; /// @dev restricts calls to board members modifier onlyBoardMember() { require(boardMembers[msg.sender], "Sender must be a Board Member"); _; } /// @dev restricts calls to the board itself (these can only be called from a voted proposal) modifier onlyBoard() { require(msg.sender == address(this), "Sender must the Board"); _; } /// @dev Events event NewProposal( uint256 proposalID, string indexed proposalType, bytes proposalPayload ); event Voted(address boardMember, uint256 proposalId); event ProposalApprovedAndEnforced( uint256 proposalID, bytes payload, bool success, bytes returnData ); event Deposit(uint256 value); /** * @dev Constructor * @param _initialMembers - Initial board's members * @param _minVotes - minimum votes to approve a proposal * @param _proposalTypes - Proposal types to add upon deployment * @param _ProposalTypeDescriptions - Description of the proposal types */ constructor( address[] memory _initialMembers, uint256 _minVotes, bytes4[] memory _proposalTypes, string[] memory _ProposalTypeDescriptions ) public { require(_minVotes > 0, "Should require at least 1 vote"); require( _initialMembers.length >= _minVotes, "Member list length must be equal or higher than minVotes" ); for (uint256 i = 0; i < _initialMembers.length; i++) { require( !boardMembers[_initialMembers[i]], "Duplicate Board Member sent" ); boardMembersList.push(_initialMembers[i]); boardMembers[_initialMembers[i]] = true; } minVotes = _minVotes; // setting up default proposalTypes (board management txs) proposalTypes["addProposalType"] = 0xeaa0dff1; proposalTypes["removeProposalType"] = 0x746d26b5; proposalTypes["changeMinVotes"] = 0x9bad192a; proposalTypes["addBoardMember"] = 0x1eac03ae; proposalTypes["removeBoardMember"] = 0x39a169f9; proposalTypes["replaceBoardMember"] = 0xbec44b4f; // setting up user provided approved proposalTypes if (_proposalTypes.length > 0) { require( _proposalTypes.length == _ProposalTypeDescriptions.length, "Proposal types and descriptions do not match" ); for (uint256 i = 0; i < _proposalTypes.length; i++) proposalTypes[_ProposalTypeDescriptions[i]] = _proposalTypes[i]; } } /** * @dev Adds a proposal and vote on it (onlyMember) * @notice every proposal is a transaction to be executed by the board transaction type of proposal have to be previously approved (function sig) * @param _type - proposal type * @param _data - proposal data (ABI encoded) * @param _destination - address to send the transaction to * @param _value - value of the transaction * @return proposalID The ID of the proposal */ function addProposal( string memory _type, bytes memory _data, address payable _destination, uint256 _value ) public onlyBoardMember returns (uint256 proposalID) { require(proposalTypes[_type] != bytes4(0x0), "Invalid proposal type"); totalProposals++; proposalID = totalProposals; Proposal memory prop = Proposal( _type, _destination, _value, 0, false, true, _data, false, bytes("") ); proposals[proposalID] = prop; emit NewProposal(proposalID, _type, _data); // proposer automatically votes require(vote(proposalID), "Voting on the new proposal failed"); return proposalID; } /** * @dev Vote on a given proposal (onlyMember) * @param _proposalID - Proposal ID * @return True if success */ function vote(uint256 _proposalID) public onlyBoardMember returns (bool) { require(proposals[_proposalID].exists, "The proposal is not found"); require( !proposals[_proposalID].voters[msg.sender], "This board member has voted already" ); require( !proposals[_proposalID].executed, "This proposal has been approved and enforced" ); proposals[_proposalID].votes++; proposals[_proposalID].voters[msg.sender] = true; emit Voted(msg.sender, _proposalID); if (proposals[_proposalID].votes >= minVotes) executeProposal(_proposalID); return true; } /** * @dev Executes a proposal (internal) * @param _proposalID - Proposal ID */ function executeProposal(uint256 _proposalID) internal { Proposal memory prop = proposals[_proposalID]; bytes memory payload = abi.encodePacked( proposalTypes[prop.proposalType], prop.proposal ); proposals[_proposalID].executed = true; (bool success, bytes memory returnData) = prop.destination.call{value: prop.value}(payload); proposals[_proposalID].success = success; proposals[_proposalID].returnData = returnData; emit ProposalApprovedAndEnforced( _proposalID, payload, success, returnData ); } /** * @dev Adds a proposal type (onlyBoard) * @param _id - The name of the proposal Type * @param _signature - 4 byte signature of the function to be called * @return True if success */ function addProposalType(string memory _id, bytes4 _signature) public onlyBoard returns (bool) { proposalTypes[_id] = _signature; return true; } /** * @dev Removes a proposal type (onlyBoard) * @param _id - The name of the proposal Type * @return True if success */ function removeProposalType(string memory _id) public onlyBoard returns (bool) { proposalTypes[_id] = bytes4(""); return true; } /** * @dev Changes the amount of votes needed to approve a proposal (onlyBoard) * @param _minVotes - New minimum quorum to approve proposals * @return True if success */ function changeMinVotes(uint256 _minVotes) public onlyBoard returns (bool) { require(_minVotes > 0, "MinVotes cannot be less than 0"); require( _minVotes <= boardMembersList.length, "MinVotes lower than number of members" ); minVotes = _minVotes; return true; } /** * @dev Adds a board member (onlyBoard) * @param _newMember - New member to be added * @return True if success */ function addBoardMember(address _newMember) public onlyBoard returns (bool) { require(!boardMembers[_newMember], "Duplicate Board Member sent"); boardMembersList.push(_newMember); boardMembers[_newMember] = true; if (boardMembersList.length > 1 && minVotes == 0) { minVotes = 1; } return true; } /** * @dev Removes a board member (onlyBoard) * @param _member - Member to be added * @return True if success */ function removeBoardMember(address _member) public onlyBoard returns (bool) { boardMembers[_member] = false; for (uint256 i = 0; i < boardMembersList.length; i++) { if (boardMembersList[i] == _member) { boardMembersList[i] = boardMembersList[boardMembersList.length - 1]; boardMembersList.pop(); } } if (boardMembersList.length < minVotes) { minVotes = boardMembersList.length; } return true; } /** * @dev Replaces a board member (onlyBoard) * @param _oldMember - Old member to be replaced * @param _newMember - New member to be added * @return True if success */ function replaceBoardMember(address _oldMember, address _newMember) public onlyBoard returns (bool) { require(removeBoardMember(_oldMember), "Failed to remove old member"); return addBoardMember(_newMember); } /** * @dev Receive */ receive() external payable { emit Deposit(msg.value); } }
* @dev Adds a new Controller @param _controller - Controller to be added @return True if success/
function newController(address _controller) public onlyController returns (bool) { require(!controllers[_controller], "Already a controller"); require(_controller != address(0), "Invalid Controller address"); require( msg.sender != _controller, "The sender cannot vote to include himself" ); controllers[_controller] = true; controllerList.push(_controller); return true; }
23,674
[ 1, 3655, 279, 394, 6629, 225, 389, 5723, 300, 6629, 358, 506, 3096, 327, 1053, 309, 2216, 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, 394, 2933, 12, 2867, 389, 5723, 13, 203, 3639, 1071, 203, 3639, 1338, 2933, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 5, 20171, 63, 67, 5723, 6487, 315, 9430, 279, 2596, 8863, 203, 3639, 2583, 24899, 5723, 480, 1758, 12, 20, 3631, 315, 1941, 6629, 1758, 8863, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 480, 389, 5723, 16, 203, 5411, 315, 1986, 5793, 2780, 12501, 358, 2341, 366, 381, 2890, 6, 203, 3639, 11272, 203, 3639, 12403, 63, 67, 5723, 65, 273, 638, 31, 203, 3639, 2596, 682, 18, 6206, 24899, 5723, 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 ]
//Address: 0x3d63da14a12a559ad081f291ae3a6f34d69be159 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 6/24/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface GACR { function transfer(address to, uint256 value) external returns (bool); function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); function totalSupply() external view returns (uint256); function setTeamAddress(address _teamFund) external; function transferOwnership(address newOwner) external; } contract Crowdsale is Ownable { using SafeMath for uint256; // ICO stage enum CrowdsaleStage { PreICO, ICO } CrowdsaleStage public stage = CrowdsaleStage.PreICO; // By default it's Pre Sale // Token distribution uint256 public constant maxTokens = 50000000*1e18; // max of GACR tokens uint256 public constant tokensForSale = 28500000*1e18; // 57% uint256 public constant tokensForBounty = 1500000*1e18; // 3% uint256 public constant tokensForAdvisors = 3000000*1e18; // 6% uint256 public constant tokensForTeam = 9000000*1e18; // 18% uint256 public tokensForEcosystem = 8000000*1e18; // 16% // Start & End time of Crowdsale uint256 startTime = 1522494000; // 2018-03-31T11:00:00 uint256 endTime = 1539169200; // 2018-10-10T11:00:00 // The token being sold GACR public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Limit for total contributions uint256 public cap; // KYC for ICO mapping(address => bool) public whitelist; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev Event for whitelist update * @param purchaser who add to whitelist * @param status of purchased for whitelist */ event WhitelistUpdate(address indexed purchaser, bool status); /** * @dev Event for crowdsale finalize */ event Finalized(); /** * @param _cap ether cap for Crowdsale * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to */ constructor(uint256 _cap, uint256 _rate, address _wallet, address _token) public { require(_cap > 0); require(_rate > 0); require(_wallet != address(0)); cap = _cap; rate = _rate; wallet = _wallet; token = GACR(_token); } /** * @dev Check that sale is on */ modifier saleIsOn() { require(now > startTime && now < endTime); _; } //note: only for test //function setNowTime(uint value) public onlyOwner { // require(value != 0); // _nowTime = value; //} /** * @dev Buy tokens */ function buyTokens(address _beneficiary) saleIsOn public payable { uint256 _weiAmount = msg.value; require(_beneficiary != address(0)); require(_weiAmount != 0); require(weiRaised.add(_weiAmount) <= cap); require(stage==CrowdsaleStage.PreICO || (stage==CrowdsaleStage.ICO && isWhitelisted(_beneficiary))); // calculate token amount to be created uint256 _tokenAmount = _weiAmount.mul(rate); // bonus calculation uint256 bonusTokens = 0; if (stage == CrowdsaleStage.PreICO) { if (_tokenAmount >= 50e18 && _tokenAmount < 3000e18) { bonusTokens = _tokenAmount.mul(23).div(100); } else if (_tokenAmount >= 3000e18 && _tokenAmount < 15000e18) { bonusTokens = _tokenAmount.mul(27).div(100); } else if (_tokenAmount >= 15000e18 && _tokenAmount < 30000e18) { bonusTokens = _tokenAmount.mul(30).div(100); } else if (_tokenAmount >= 30000e18) { bonusTokens = _tokenAmount.mul(35).div(100); } } else if (stage == CrowdsaleStage.ICO) { uint256 _nowTime = now; if (_nowTime >= 1531486800 && _nowTime < 1532696400) { bonusTokens = _tokenAmount.mul(18).div(100); } else if (_nowTime >= 1532696400 && _nowTime < 1533906000) { bonusTokens = _tokenAmount.mul(15).div(100); } else if (_nowTime >= 1533906000 && _nowTime < 1535115600) { bonusTokens = _tokenAmount.mul(12).div(100); } else if (_nowTime >= 1535115600 && _nowTime < 1536325200) { bonusTokens = _tokenAmount.mul(9).div(100); } else if (_nowTime >= 1536325200 && _nowTime < 1537534800) { bonusTokens = _tokenAmount.mul(6).div(100); } else if (_nowTime >= 1537534800 && _nowTime < endTime) { bonusTokens = _tokenAmount.mul(3).div(100); } } _tokenAmount += bonusTokens; // check limit for sale require(tokensForSale >= (token.totalSupply() + _tokenAmount)); // update state weiRaised = weiRaised.add(_weiAmount); token.mint(_beneficiary, _tokenAmount); emit TokenPurchase(msg.sender, _beneficiary, _weiAmount, _tokenAmount); wallet.transfer(_weiAmount); } /** * @dev Payable function */ function () external payable { buyTokens(msg.sender); } /** * @dev Change Crowdsale Stage. * Options: PreICO, ICO */ function setCrowdsaleStage(uint value) public onlyOwner { CrowdsaleStage _stage; if (uint256(CrowdsaleStage.PreICO) == value) { _stage = CrowdsaleStage.PreICO; } else if (uint256(CrowdsaleStage.ICO) == value) { _stage = CrowdsaleStage.ICO; } stage = _stage; } /** * @dev Set new rate (protection from strong volatility) */ function setNewRate(uint _newRate) public onlyOwner { require(_newRate > 0); rate = _newRate; } /** * @dev Set hard cap (protection from strong volatility) */ function setHardCap(uint256 _newCap) public onlyOwner { require(_newCap > 0); cap = _newCap; } /** * @dev Set new wallet */ function changeWallet(address _newWallet) public onlyOwner { require(_newWallet != address(0)); wallet = _newWallet; } /** * @dev Add/Remove to whitelist array of addresses based on boolean status */ function updateWhitelist(address[] addresses, bool status) public onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { address contributorAddress = addresses[i]; whitelist[contributorAddress] = status; emit WhitelistUpdate(contributorAddress, status); } } /** * @dev Check that address is exist in whitelist */ function isWhitelisted(address contributor) public constant returns (bool) { return whitelist[contributor]; } /** * @dev Function to mint tokens */ function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { return token.mint(_to, _amount); } /** * @dev Return ownership to previous owner */ function returnOwnership() onlyOwner public returns (bool) { token.transferOwnership(owner); } /** * @dev Finish Crowdsale */ function finish(address _bountyFund, address _advisorsFund, address _ecosystemFund, address _teamFund) public onlyOwner { require(_bountyFund != address(0)); require(_advisorsFund != address(0)); require(_ecosystemFund != address(0)); require(_teamFund != address(0)); emit Finalized(); // unsold tokens to ecosystem (perhaps further they will be burnt) uint256 unsoldTokens = tokensForSale - token.totalSupply(); if (unsoldTokens > 0) { tokensForEcosystem = tokensForEcosystem + unsoldTokens; } // distribute token.mint(_bountyFund,tokensForBounty); token.mint(_advisorsFund,tokensForAdvisors); token.mint(_ecosystemFund,tokensForEcosystem); token.mint(_teamFund,tokensForTeam); // finish token.finishMinting(); // freeze team tokens token.setTeamAddress(_teamFund); } }
check limit for sale
require(tokensForSale >= (token.totalSupply() + _tokenAmount));
15,873,700
[ 1, 1893, 1800, 364, 272, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 7860, 1290, 30746, 1545, 261, 2316, 18, 4963, 3088, 1283, 1435, 397, 389, 2316, 6275, 10019, 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 ]
./full_match/5/0xD6ee3B39dD53b753E3253Befa40222602406409B/sources/src/Vault.sol
@notice Add an array of new depositors to the allow list @param depositors Array of new depositors
function addDepositorsToAllowlist(address[] calldata depositors) external onlyVaultAdmin { for (uint256 i = 0; i < depositors.length; i++) { _depositorsAllowlist.add(depositors[i]); } }
1,876,145
[ 1, 986, 392, 526, 434, 394, 443, 1724, 1383, 358, 326, 1699, 666, 225, 443, 1724, 1383, 1510, 434, 394, 443, 1724, 1383, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 758, 1724, 1383, 774, 7009, 1098, 12, 2867, 8526, 745, 892, 443, 1724, 1383, 13, 3903, 1338, 12003, 4446, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 443, 1724, 1383, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 323, 1724, 1383, 7009, 1098, 18, 1289, 12, 323, 1724, 1383, 63, 77, 19226, 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 ]
./full_match/3/0x4f7df3Da3e2aC27B8446A2C6799352782107ca4D/sources/browser/Vesting.sol
amount they can withdraw
vested_total = vesting_seconds.mul(vest_per_second_sats).add(s.initial);
14,223,031
[ 1, 8949, 2898, 848, 598, 9446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7734, 331, 3149, 67, 4963, 273, 331, 10100, 67, 7572, 18, 16411, 12, 26923, 67, 457, 67, 8538, 67, 87, 2323, 2934, 1289, 12, 87, 18, 6769, 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 ]
pragma solidity ^0.4.24; contract AcceptsExchange { Exchange public tokenContract; constructor(address _tokenContract) public { tokenContract = Exchange(_tokenContract); } modifier onlyTokenContract { require(msg.sender == address(tokenContract)); _; } /** * @dev Standard ERC677 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract Exchange { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier notContract() { require (msg.sender == tx.origin); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } uint ACTIVATION_TIME = 1539302400; // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[msg.sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[msg.sender] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[msg.sender] = SafeMath.add(ambassadorAccumulatedQuota_[msg.sender], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, bool isReinvest, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn, uint256 estimateTokens, bool isTransfer ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "EXCHANGE"; string public symbol = "SHARES"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 20; // 20% dividend fee on each buy uint8 constant internal startExitFee_ = 40; // 40 % dividends for token selling uint8 constant internal finalExitFee_ = 20; // 20% dividends for token selling after step uint8 constant internal fundFee_ = 5; // 5% to stock game uint256 constant internal exitFeeFallDuration_ = 30 days; //Exit fee falls over period of 30 days uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // Address to send the 5% Fee address public giveEthFundAddress = 0x0; bool public finalizedEthFundAddress = false; uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract uint256 public totalEthFundCollected; // total ETH charity collected in this contract // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 25e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 7 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // To whitelist game contracts on the platform mapping(address => bool) public canAcceptTokens_; // contracts, which can accept the exchanges tokens /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0x3db1e274bf36824cf655beddb92a90c04906e04b] = true; // add the ambassadors here - Tokens will be distributed to these addresses from main premine ambassadors_[0x3db1e274bf36824cf655beddb92a90c04906e04b] = true; ambassadors_[0x7191cbd8bbcacfe989aa60fb0be85b47f922fe21] = true; ambassadors_[0xEafE863757a2b2a2c5C3f71988b7D59329d09A78] = true; ambassadors_[0x5138240E96360ad64010C27eB0c685A8b2eDE4F2] = true; ambassadors_[0xC558895aE123BB02b3c33164FdeC34E9Fb66B660] = true; ambassadors_[0x4ffE17a2A72bC7422CB176bC71c04EE6D87cE329] = true; ambassadors_[0xEc31176d4df0509115abC8065A8a3F8275aafF2b] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { require(tx.gasprice <= 0.05 szabo); purchaseInternal(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { require(tx.gasprice <= 0.05 szabo); purchaseInternal(msg.value, 0x0); } function updateFundAddress(address _newAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _newAddress; } function finalizeFundAddress(address _finalAddress) onlyAdministrator() public { require(finalizedEthFundAddress == false); giveEthFundAddress = _finalAddress; finalizedEthFundAddress = true; } function payFund() payable onlyAdministrator() public { uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); require(ethToPay > 0); totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay); if(!giveEthFundAddress.call.value(ethToPay).gas(400000)()) { totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, ethToPay); } } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0, true); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(false); } /** * Withdraws all of the callers earnings. */ function withdraw(bool _isTransfer) onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code uint256 _estimateTokens = calculateTokensReceived(_dividends); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends, _estimateTokens, _isTransfer); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); // Take out dividends and then _fundPayout uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); // Add ethereum to send to fund totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(true); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) { require(_to != address(0)); require(canAcceptTokens_[_to] == true); // security check that contract approved by the exchange require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { AcceptsExchange receiver = AcceptsExchange(_to); require(receiver.tokenFallback(msg.sender, _value, _data)); } return true; } /** * Additional check that the game address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private constant returns (bool is_contract) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add or remove game contract, which can accept tokens */ function setCanAcceptTokens(address _address, bool _value) onlyAdministrator() public { canAcceptTokens_[_address] = _value; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee()), 100); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout); return _taxedEthereum; } /** * Function for the frontend to show ether waiting to be send to fund in contract */ function etherToSendFund() public view returns(uint256) { return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved); } /** * Function for getting the current exitFee */ function exitFee() public view returns (uint8) { if ( now < ACTIVATION_TIME) { return startExitFee_; } uint256 secondsPassed = now - ACTIVATION_TIME; if (secondsPassed >= exitFeeFallDuration_) { return finalExitFee_; } uint8 totalChange = startExitFee_ - finalExitFee_; uint8 currentChange = uint8(totalChange * secondsPassed / exitFeeFallDuration_); uint8 currentFee = startExitFee_- currentChange; return currentFee; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // Make sure we will send back excess if user sends more then 2 ether before 80 ETH in contract function purchaseInternal(uint256 _incomingEthereum, address _referredBy) notContract()// no contracts allowed internal returns(uint256) { uint256 purchaseEthereum = _incomingEthereum; uint256 excess; if(purchaseEthereum > 2 ether) { // check if the transaction is over 2 ether if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 80 ether) { // if so check the contract is less then 80 ether purchaseEthereum = 2 ether; excess = SafeMath.sub(_incomingEthereum, purchaseEthereum); } } purchaseTokens(purchaseEthereum, _referredBy, false); if (excess > 0) { msg.sender.transfer(excess); } } function purchaseTokens(uint256 _incomingEthereum, address _referredBy, bool _isReinvest) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout); totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poor russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy, _isReinvest, now, buyPrice()); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
---------- HELPERS AND CALCULATORS ----------*/* Method to view the current Ethereum stored in the contract Example: totalEthereumBalance()/
function totalEthereumBalance() public view returns(uint) { return address(this).balance; }
1,511,670
[ 1, 15392, 225, 22557, 3194, 55, 4116, 385, 1013, 39, 1506, 3575, 55, 225, 12181, 19, 2985, 358, 1476, 326, 783, 512, 18664, 379, 4041, 316, 326, 6835, 5090, 30, 2078, 41, 18664, 379, 13937, 1435, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 2078, 41, 18664, 379, 13937, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 12, 11890, 13, 203, 565, 288, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { ISwapManager } from "./ISwapManager.sol"; interface IUniswapV2Router02 { function WETH() external pure returns (address); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } contract UniswapManager is ISwapManager { using SafeMath for uint256; using SafeERC20 for IERC20; address public immutable uniswapV2Router; /** * @param _uniswapV2Router UniswapV2Router02 address. */ constructor(address _uniswapV2Router) public { uniswapV2Router = _uniswapV2Router; } /** * Executes Eth <> token swap using the uniswapRouterV2. */ function swapEthToToken( uint256 _srcAmount, IERC20 _dstToken, uint256 _maxDstAmount, address _beneficiary ) external payable override returns (uint256 dstAmount, uint256 srcReminder) { address[] memory path = new address[](2); path[0] = IUniswapV2Router02(uniswapV2Router).WETH(); path[1] = address(_dstToken); uint256[] memory amounts = IUniswapV2Router02(uniswapV2Router).swapExactETHForTokens{ value: _srcAmount }( _maxDstAmount, path, _beneficiary, block.timestamp ); // Fill return vars dstAmount = amounts[1]; srcReminder = _srcAmount.sub(amounts[0]); } /** * Executes a token <> token swap using the uniswapRouterV2. */ function swapTokenToToken( IERC20 _srcToken, IERC20 _dstToken, uint256 _srcAmount, uint256 _maxDstAmount, address _beneficiary ) external override returns (uint256 dstAmount, uint256 srcRemainder) { IERC20(_srcToken).safeIncreaseAllowance(uniswapV2Router, _srcAmount); address[] memory path = new address[](2); path[0] = address(_srcToken); path[1] = address(_dstToken); uint256[] memory amounts = IUniswapV2Router02(uniswapV2Router).swapExactTokensForTokens( _srcAmount, _maxDstAmount, path, _beneficiary, block.timestamp ); // Fill return vars dstAmount = amounts[1]; srcRemainder = _srcAmount.sub(amounts[0]); } }
* Executes a token <> token swap using the uniswapRouterV2./ Fill return vars
function swapTokenToToken( IERC20 _srcToken, IERC20 _dstToken, uint256 _srcAmount, uint256 _maxDstAmount, address _beneficiary ) external override returns (uint256 dstAmount, uint256 srcRemainder) { IERC20(_srcToken).safeIncreaseAllowance(uniswapV2Router, _srcAmount); address[] memory path = new address[](2); path[0] = address(_srcToken); path[1] = address(_dstToken); uint256[] memory amounts = IUniswapV2Router02(uniswapV2Router).swapExactTokensForTokens( _srcAmount, _maxDstAmount, path, _beneficiary, block.timestamp ); dstAmount = amounts[1]; srcRemainder = _srcAmount.sub(amounts[0]); }
1,064,451
[ 1, 9763, 279, 1147, 2813, 1147, 7720, 1450, 326, 640, 291, 91, 438, 8259, 58, 22, 18, 19, 14192, 327, 4153, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7720, 1345, 774, 1345, 12, 203, 3639, 467, 654, 39, 3462, 389, 4816, 1345, 16, 203, 3639, 467, 654, 39, 3462, 389, 11057, 1345, 16, 203, 3639, 2254, 5034, 389, 4816, 6275, 16, 203, 3639, 2254, 5034, 389, 1896, 15295, 6275, 16, 203, 3639, 1758, 389, 70, 4009, 74, 14463, 814, 203, 565, 262, 203, 3639, 3903, 3849, 1135, 261, 11890, 5034, 3046, 6275, 16, 2254, 5034, 1705, 1933, 25407, 13, 203, 565, 288, 203, 3639, 467, 654, 39, 3462, 24899, 4816, 1345, 2934, 4626, 382, 11908, 7009, 1359, 12, 318, 291, 91, 438, 58, 22, 8259, 16, 389, 4816, 6275, 1769, 203, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 203, 3639, 589, 63, 20, 65, 273, 1758, 24899, 4816, 1345, 1769, 203, 3639, 589, 63, 21, 65, 273, 1758, 24899, 11057, 1345, 1769, 203, 203, 3639, 2254, 5034, 8526, 3778, 30980, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 318, 291, 91, 438, 58, 22, 8259, 2934, 22270, 14332, 5157, 1290, 5157, 12, 203, 5411, 389, 4816, 6275, 16, 203, 5411, 389, 1896, 15295, 6275, 16, 203, 5411, 589, 16, 203, 5411, 389, 70, 4009, 74, 14463, 814, 16, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 203, 3639, 3046, 6275, 273, 30980, 63, 21, 15533, 203, 3639, 1705, 1933, 25407, 273, 389, 4816, 6275, 18, 1717, 12, 8949, 87, 63, 20, 19226, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xD9CcbFc602110a447b1A7Ac05204c1eae2A8CdCD/sources/MagePunks.sol
@dev sets royalties address for royalties addon for 2981
function setRoyaltiesAddress(address _royaltiesAddress) public onlyOwner { super._setRoyaltiesAddress(_royaltiesAddress); }
13,261,511
[ 1, 4424, 721, 93, 2390, 606, 1758, 364, 721, 93, 2390, 606, 15466, 364, 576, 10689, 21, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 54, 13372, 2390, 606, 1887, 12, 2867, 389, 3800, 2390, 606, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 2240, 6315, 542, 54, 13372, 2390, 606, 1887, 24899, 3800, 2390, 606, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.11; import "./oraclizeAPI.sol"; import "./roulette.sol"; contract Oracle is usingOraclize{ // Oracle, manages the generation of the random number via Oraclize //Random.org API-KEY:7dab0ab9-8f2f-4b2d-8ed1-b62cc1454c00 event LogOraclizeFee(uint fee); event LogQuerySent(string description); event LogQueryNotSent(string description); event LogQueryDone(bytes32 id, string result); bytes32 rng; uint urng; constructor()public payable{ //OAR needed for testnet with oraclize. for ethereum-bridge //https://medium.com/coinmonks/how-to-create-a-dapp-using-truffle-oraclize-ethereum-bridge-and-webpack-9cb84b8f6bcb //address is deterministic, does not change. OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } function getRandomNumber() public view returns (uint){ return urng; } function generateRandomNumber() public payable { //https://www.sitepoint.com/solidity-pitfalls-random-number-generation-for-ethereum/ //simple randomizer, only for test purposes. // return uint256(keccak256(abi.encodePacked(now)))%37; uint fee = oraclize_getPrice("URL"); emit LogOraclizeFee(fee); bytes32 queryId = oraclize_query("URL", "json(https://api.random.org/json-rpc/1/invoke).result.random.data.0", '\n{"jsonrpc":"2.0","method":"generateIntegers","params":{"apiKey":"7dab0ab9-8f2f-4b2d-8ed1-b62cc1454c00","n":1,"min":0,"max":36,"replacement":true,"base":10},"id":1}'); //alternative: Use WolframAlpha // queryId = oraclize_query("WolframAlpha", "random number between 0 and 37"); //to debug, check with ethereum-bridge in terminal emit LogQuerySent("sent query"); } function __callback(bytes32 myQueryId, string memory result) public { //https://medium.com/aigang-network/how-ethereum-contract-can-communicate-with-external-data-source-2e32616ea180 urng = parseInt(result); emit LogQueryDone(myQueryId, result); } }
Oracle, manages the generation of the random number via OraclizeRandom.org API-KEY:7dab0ab9-8f2f-4b2d-8ed1-b62cc1454c00
contract Oracle is usingOraclize{ event LogOraclizeFee(uint fee); event LogQuerySent(string description); event LogQueryNotSent(string description); event LogQueryDone(bytes32 id, string result); bytes32 rng; uint urng; constructor()public payable{ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } function getRandomNumber() public view returns (uint){ return urng; } function generateRandomNumber() public payable { uint fee = oraclize_getPrice("URL"); emit LogOraclizeFee(fee); bytes32 queryId = oraclize_query("URL", emit LogQuerySent("sent query"); } function __callback(bytes32 myQueryId, string memory result) public { urng = parseInt(result); emit LogQueryDone(myQueryId, result); } }
15,853,951
[ 1, 23601, 16, 20754, 281, 326, 9377, 434, 326, 2744, 1300, 3970, 531, 354, 830, 554, 8529, 18, 3341, 1491, 17, 3297, 30, 27, 72, 378, 20, 378, 29, 17, 28, 74, 22, 74, 17, 24, 70, 22, 72, 17, 28, 329, 21, 17, 70, 8898, 952, 3461, 6564, 71, 713, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 28544, 353, 1450, 51, 354, 830, 554, 95, 203, 203, 203, 203, 565, 871, 1827, 51, 354, 830, 554, 14667, 12, 11890, 14036, 1769, 203, 565, 871, 1827, 1138, 7828, 12, 1080, 2477, 1769, 203, 565, 871, 1827, 1138, 1248, 7828, 12, 1080, 2477, 1769, 203, 565, 871, 1827, 1138, 7387, 12, 3890, 1578, 612, 16, 533, 563, 1769, 203, 565, 1731, 1578, 11418, 31, 203, 565, 2254, 18412, 75, 31, 203, 203, 565, 3885, 1435, 482, 8843, 429, 95, 203, 3639, 531, 985, 273, 531, 354, 830, 554, 3178, 4301, 45, 12, 20, 92, 26, 74, 24, 7140, 39, 28, 15259, 26, 7142, 8942, 73, 37, 22, 2138, 41, 11180, 9676, 42, 28, 311, 3028, 26, 39, 27, 74, 21, 7358, 24, 5877, 1769, 203, 565, 289, 203, 203, 565, 445, 20581, 1854, 1435, 1071, 1476, 1135, 261, 11890, 15329, 203, 3639, 327, 18412, 75, 31, 203, 565, 289, 203, 203, 565, 445, 2103, 8529, 1854, 1435, 1071, 8843, 429, 225, 288, 203, 203, 3639, 2254, 14036, 273, 578, 10150, 554, 67, 588, 5147, 2932, 1785, 8863, 203, 3639, 3626, 1827, 51, 354, 830, 554, 14667, 12, 21386, 1769, 203, 3639, 1731, 1578, 843, 548, 273, 578, 10150, 554, 67, 2271, 2932, 1785, 3113, 203, 203, 203, 3639, 3626, 1827, 1138, 7828, 2932, 7569, 843, 8863, 203, 565, 289, 203, 203, 565, 445, 1001, 3394, 12, 3890, 1578, 3399, 1138, 548, 16, 533, 3778, 563, 13, 1071, 288, 203, 3639, 18412, 75, 273, 5395, 12, 2088, 1769, 203, 3639, 3626, 1827, 1138, 2 ]
// SPDX-License-Identifier: MIT // Inspired on Timelock.sol from Compound. // Special thanks to BoringCrypto and Mudit Gupta for their feedback. pragma solidity ^0.8.0; import "../access/AccessControl.sol"; import "./RevertMsgExtractor.sol"; import "./IsContract.sol"; interface ITimelock { struct Call { address target; bytes data; } function setDelay(uint32 delay_) external; function propose(Call[] calldata functionCalls) external returns (bytes32 txHash); function proposeRepeated(Call[] calldata functionCalls, uint256 salt) external returns (bytes32 txHash); function approve(bytes32 txHash) external returns (uint32); function execute(Call[] calldata functionCalls) external returns (bytes[] calldata results); function executeRepeated(Call[] calldata functionCalls, uint256 salt) external returns (bytes[] calldata results); } contract Timelock is ITimelock, AccessControl { using IsContract for address; enum STATE { UNKNOWN, PROPOSED, APPROVED } struct Proposal { STATE state; uint32 eta; } uint32 public constant GRACE_PERIOD = 14 days; uint32 public constant MINIMUM_DELAY = 2 days; uint32 public constant MAXIMUM_DELAY = 30 days; event DelaySet(uint256 indexed delay); event Proposed(bytes32 indexed txHash); event Approved(bytes32 indexed txHash, uint32 eta); event Executed(bytes32 indexed txHash); uint32 public delay; mapping (bytes32 => Proposal) public proposals; constructor(address governor) AccessControl() { delay = 0; // delay is set to zero initially to allow testing and configuration. Set to a different value to go live. // Each role in AccessControl.sol is a 1-of-n multisig. It is recommended that trusted individual accounts get `propose` // and `execute` permissions, while only the governor keeps `approve` permissions. The governor should keep the `propose` // and `execute` permissions, but use them only in emergency situations (such as all trusted individuals going rogue). _grantRole(ITimelock.propose.selector, governor); _grantRole(ITimelock.proposeRepeated.selector, governor); _grantRole(ITimelock.approve.selector, governor); _grantRole(ITimelock.execute.selector, governor); _grantRole(ITimelock.executeRepeated.selector, governor); // Changing the delay must now be executed through this Timelock contract _grantRole(ITimelock.setDelay.selector, address(this)); // bytes4(keccak256("setDelay(uint256)")) // Granting roles (propose, approve, execute, setDelay) must now be executed through this Timelock contract _grantRole(ROOT, address(this)); _revokeRole(ROOT, msg.sender); } /// @dev Change the delay for approved proposals function setDelay(uint32 delay_) external override auth { require(delay_ >= MINIMUM_DELAY, "Must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Must not exceed maximum delay."); delay = delay_; emit DelaySet(delay_); } /// @dev Compute the hash for a proposal function hash(Call[] calldata functionCalls) external pure returns (bytes32 txHash) { return _hash(functionCalls, 0); } /// @dev Compute the hash for a proposal, with other identical proposals existing /// @param salt Unique identifier for the transaction when repeatedly proposed. Chosen by governor. function hashRepeated(Call[] calldata functionCalls, uint256 salt) external pure returns (bytes32 txHash) { return _hash(functionCalls, salt); } /// @dev Compute the hash for a proposal function _hash(Call[] calldata functionCalls, uint256 salt) private pure returns (bytes32 txHash) { txHash = keccak256(abi.encode(functionCalls, salt)); } /// @dev Propose a transaction batch for execution function propose(Call[] calldata functionCalls) external override auth returns (bytes32 txHash) { return _propose(functionCalls, 0); } /// @dev Propose a transaction batch for execution, with other identical proposals existing /// @param salt Unique identifier for the transaction when repeatedly proposed. Chosen by governor. function proposeRepeated(Call[] calldata functionCalls, uint256 salt) external override auth returns (bytes32 txHash) { return _propose(functionCalls, salt); } /// @dev Propose a transaction batch for execution function _propose(Call[] calldata functionCalls, uint256 salt) private returns (bytes32 txHash) { txHash = keccak256(abi.encode(functionCalls, salt)); require(proposals[txHash].state == STATE.UNKNOWN, "Already proposed."); proposals[txHash].state = STATE.PROPOSED; emit Proposed(txHash); } /// @dev Approve a proposal and set its eta function approve(bytes32 txHash) external override auth returns (uint32 eta) { Proposal memory proposal = proposals[txHash]; require(proposal.state == STATE.PROPOSED, "Not proposed."); eta = uint32(block.timestamp) + delay; proposal.state = STATE.APPROVED; proposal.eta = eta; proposals[txHash] = proposal; emit Approved(txHash, eta); } /// @dev Execute a proposal function execute(Call[] calldata functionCalls) external override auth returns (bytes[] memory results) { return _execute(functionCalls, 0); } /// @dev Execute a proposal, among several identical ones /// @param salt Unique identifier for the transaction when repeatedly proposed. Chosen by governor. function executeRepeated(Call[] calldata functionCalls, uint256 salt) external override auth returns (bytes[] memory results) { return _execute(functionCalls, salt); } /// @dev Execute a proposal function _execute(Call[] calldata functionCalls, uint256 salt) private returns (bytes[] memory results) { bytes32 txHash = keccak256(abi.encode(functionCalls, salt)); Proposal memory proposal = proposals[txHash]; require(proposal.state == STATE.APPROVED, "Not approved."); require(uint32(block.timestamp) >= proposal.eta, "ETA not reached."); require(uint32(block.timestamp) <= proposal.eta + GRACE_PERIOD, "Proposal is stale."); delete proposals[txHash]; results = new bytes[](functionCalls.length); for (uint256 i = 0; i < functionCalls.length; i++){ require(functionCalls[i].target.isContract(), "Call to a non-contract"); (bool success, bytes memory result) = functionCalls[i].target.call(functionCalls[i].data); if (!success) revert(RevertMsgExtractor.getRevertMsg(result)); results[i] = result; } emit Executed(txHash); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "hardhat/console.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes4` identifier. These are expected to be the * signatures for all the functions in the contract. Special roles should be exposed * in the external API and be unique: * * ``` * bytes4 public constant ROOT = 0x00000000; * ``` * * Roles represent restricted access to a function call. For that purpose, use {auth}: * * ``` * function foo() public auth { * ... * } * ``` * * 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 `ROOT`, 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 `ROOT` 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. */ contract AccessControl { struct RoleData { mapping (address => bool) members; bytes4 adminRole; } mapping (bytes4 => RoleData) private _roles; bytes4 public constant ROOT = 0x00000000; bytes4 public constant ROOT4146650865 = 0x00000000; // Collision protection for ROOT, test with ROOT12007226833() bytes4 public constant LOCK = 0xFFFFFFFF; // Used to disable further permissioning of a function bytes4 public constant LOCK8605463013 = 0xFFFFFFFF; // Collision protection for LOCK, test with LOCK10462387368() /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role * * `ROOT` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes4 indexed role, bytes4 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call. */ event RoleGranted(bytes4 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(bytes4 indexed role, address indexed account, address indexed sender); /** * @dev Give msg.sender the ROOT role and create a LOCK role with itself as the admin role and no members. * Calling setRoleAdmin(msg.sig, LOCK) means no one can grant that msg.sig role anymore. */ constructor () { _grantRole(ROOT, msg.sender); // Grant ROOT to msg.sender _setRoleAdmin(LOCK, LOCK); // Create the LOCK role by setting itself as its own admin, creating an independent role tree } /** * @dev Each function in the contract has its own role, identified by their msg.sig signature. * ROOT can give and remove access to each function, lock any further access being granted to * a specific action, or even create other roles to delegate admin control over a function. */ modifier auth() { require (_hasRole(msg.sig, msg.sender), "Access denied"); _; } /** * @dev Allow only if the caller has been granted the admin role of `role`. */ modifier admin(bytes4 role) { require (_hasRole(_getRoleAdmin(role), msg.sender), "Only admin"); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes4 role, address account) external view returns (bool) { return _hasRole(role, account); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes4 role) external view returns (bytes4) { return _getRoleAdmin(role); } /** * @dev Sets `adminRole` as ``role``'s admin role. * If ``role``'s admin role is not `adminRole` emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setRoleAdmin(bytes4 role, bytes4 adminRole) external virtual admin(role) { _setRoleAdmin(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(bytes4 role, address account) external virtual admin(role) { _grantRole(role, account); } /** * @dev Grants all of `role` in `roles` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function grantRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _grantRole(roles[i], account); } } /** * @dev Sets LOCK as ``role``'s admin role. LOCK has no members, so this disables admin management of ``role``. * Emits a {RoleAdminChanged} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function lockRole(bytes4 role) external virtual admin(role) { _setRoleAdmin(role, LOCK); } /** * @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(bytes4 role, address account) external virtual admin(role) { _revokeRole(role, account); } /** * @dev Revokes all of `role` in `roles` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - For each `role` in `roles`, the caller must have ``role``'s admin role. */ function revokeRoles(bytes4[] memory roles, address account) external virtual { for (uint256 i = 0; i < roles.length; i++) { require (_hasRole(_getRoleAdmin(roles[i]), msg.sender), "Only admin"); _revokeRole(roles[i], 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(bytes4 role, address account) external virtual { require(account == msg.sender, "Renounce only for self"); _revokeRole(role, account); } function _hasRole(bytes4 role, address account) internal view returns (bool) { return _roles[role].members[account]; } function _getRoleAdmin(bytes4 role) internal view returns (bytes4) { return _roles[role].adminRole; } function _setRoleAdmin(bytes4 role, bytes4 adminRole) internal virtual { if (_getRoleAdmin(role) != adminRole) { _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, adminRole); } } function _grantRole(bytes4 role, address account) internal { if (!_hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, msg.sender); } } function _revokeRole(bytes4 role, address account) internal { if (_hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, msg.sender); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol pragma solidity >=0.6.0; library RevertMsgExtractor { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function getRevertMsg(bytes memory returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. returnData := add(returnData, 0x04) } return abi.decode(returnData, (string)); // All that remains is the revert string } } // SPDX-License-Identifier: MIT // Taken from Address.sol from OpenZeppelin. pragma solidity ^0.8.0; library IsContract { /// @dev Returns true if `account` is a contract. 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. return account.code.length > 0; } } // 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)); } }
Each role in AccessControl.sol is a 1-of-n multisig. It is recommended that trusted individual accounts get `propose` and `execute` permissions, while only the governor keeps `approve` permissions. The governor should keep the `propose` and `execute` permissions, but use them only in emergency situations (such as all trusted individuals going rogue). Changing the delay must now be executed through this Timelock contract Granting roles (propose, approve, execute, setDelay) must now be executed through this Timelock contract
constructor(address governor) AccessControl() { _grantRole(ITimelock.propose.selector, governor); _grantRole(ITimelock.proposeRepeated.selector, governor); _grantRole(ITimelock.approve.selector, governor); _grantRole(ITimelock.execute.selector, governor); _grantRole(ITimelock.executeRepeated.selector, governor); _grantRole(ROOT, address(this)); _revokeRole(ROOT, msg.sender); }
12,153,311
[ 1, 3442, 2478, 316, 24349, 18, 18281, 353, 279, 404, 17, 792, 17, 82, 22945, 360, 18, 2597, 353, 14553, 716, 13179, 7327, 9484, 336, 1375, 685, 4150, 68, 471, 1375, 8837, 68, 4371, 16, 1323, 1338, 326, 314, 1643, 29561, 20948, 1375, 12908, 537, 68, 4371, 18, 1021, 314, 1643, 29561, 1410, 3455, 326, 1375, 685, 4150, 68, 471, 1375, 8837, 68, 4371, 16, 1496, 999, 2182, 1338, 316, 801, 24530, 28474, 261, 87, 2648, 487, 777, 13179, 24479, 8554, 721, 75, 344, 2934, 1680, 18183, 326, 4624, 1297, 2037, 506, 7120, 3059, 333, 12652, 292, 975, 6835, 19689, 310, 4900, 261, 685, 4150, 16, 6617, 537, 16, 1836, 16, 444, 6763, 13, 1297, 2037, 506, 7120, 3059, 333, 12652, 292, 975, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 3885, 12, 2867, 314, 1643, 29561, 13, 24349, 1435, 288, 203, 203, 3639, 389, 16243, 2996, 12, 1285, 381, 292, 975, 18, 685, 4150, 18, 9663, 16, 314, 1643, 29561, 1769, 203, 3639, 389, 16243, 2996, 12, 1285, 381, 292, 975, 18, 685, 4150, 20730, 18, 9663, 16, 314, 1643, 29561, 1769, 203, 3639, 389, 16243, 2996, 12, 1285, 381, 292, 975, 18, 12908, 537, 18, 9663, 16, 314, 1643, 29561, 1769, 203, 3639, 389, 16243, 2996, 12, 1285, 381, 292, 975, 18, 8837, 18, 9663, 16, 314, 1643, 29561, 1769, 203, 3639, 389, 16243, 2996, 12, 1285, 381, 292, 975, 18, 8837, 20730, 18, 9663, 16, 314, 1643, 29561, 1769, 203, 203, 203, 3639, 389, 16243, 2996, 12, 9185, 16, 1758, 12, 2211, 10019, 203, 3639, 389, 9083, 3056, 2996, 12, 9185, 16, 1234, 18, 15330, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xDC750c9a411e3BfA0fB0Dd1248251D5831321352/sources/cache/solpp-generated-contracts/Config.sol
@title zkSync configuration constants @author Matter Labs
contract Config { uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 50000; uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000; uint8 constant CHUNK_BYTES = 9; uint8 constant ADDRESS_BYTES = 20; uint8 constant PUBKEY_HASH_BYTES = 20; uint8 constant PUBKEY_BYTES = 32; uint8 constant ETH_SIGN_RS_BYTES = 32; uint8 constant SUCCESS_FLAG_BYTES = 1; uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 127; uint32 constant MAX_ACCOUNT_ID = (2**24) - 1; uint256 constant BLOCK_PERIOD = 15 seconds; uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD; uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES; uint256 constant DEPOSIT_BYTES = 6 * CHUNK_BYTES; uint256 constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES; uint256 constant PARTIAL_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES; uint256 constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 constant FULL_EXIT_BYTES = 6 * CHUNK_BYTES; uint256 constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES; uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days; uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD/BLOCK_PERIOD; uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6; uint256 constant MASS_FULL_EXIT_PERIOD = 3 days; uint256 constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days; uint256 constant UPGRADE_NOTICE_PERIOD = 0; uint256 constant COMMIT_TIMESTAMP_NOT_OLDER = 8 hours; uint256 constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes; }
749,257
[ 1, 22888, 4047, 1664, 6810, 225, 490, 9293, 511, 5113, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1903, 288, 203, 565, 2254, 5034, 5381, 4232, 39, 3462, 67, 9147, 40, 10821, 1013, 67, 43, 3033, 67, 8283, 273, 1381, 2787, 31, 203, 203, 565, 2254, 5034, 5381, 512, 2455, 67, 9147, 40, 10821, 1013, 67, 43, 3033, 67, 8283, 273, 12619, 31, 203, 203, 565, 2254, 28, 5381, 28096, 67, 13718, 273, 2468, 31, 203, 203, 565, 2254, 28, 5381, 11689, 10203, 67, 13718, 273, 4200, 31, 203, 203, 565, 2254, 28, 5381, 23295, 3297, 67, 15920, 67, 13718, 273, 4200, 31, 203, 203, 565, 2254, 28, 5381, 23295, 3297, 67, 13718, 273, 3847, 31, 203, 203, 565, 2254, 28, 5381, 512, 2455, 67, 11260, 67, 13225, 67, 13718, 273, 3847, 31, 203, 203, 565, 2254, 28, 5381, 16561, 67, 9651, 67, 13718, 273, 404, 31, 203, 203, 565, 2254, 2313, 5381, 4552, 67, 2192, 51, 5321, 67, 3932, 67, 27511, 2056, 67, 8412, 55, 273, 12331, 31, 203, 203, 565, 2254, 1578, 5381, 4552, 67, 21690, 67, 734, 273, 261, 22, 636, 3247, 13, 300, 404, 31, 203, 203, 565, 2254, 5034, 5381, 14073, 67, 28437, 273, 4711, 3974, 31, 203, 203, 565, 2254, 5034, 5381, 5675, 1423, 1268, 67, 2204, 14865, 67, 706, 273, 374, 7507, 342, 14073, 67, 28437, 31, 203, 203, 565, 2254, 5034, 5381, 3741, 3665, 67, 13718, 273, 404, 380, 28096, 67, 13718, 31, 203, 565, 2254, 5034, 5381, 2030, 28284, 67, 13718, 273, 1666, 380, 28096, 67, 13718, 31, 203, 565, 2254, 5034, 5381, 4235, 17598, 67, 4296, 67, 12917, 67, 13718, 273, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function average(uint256 a, uint256 b) internal pure returns (uint256) { return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { 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); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) {// Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return _msgSender() == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract RewardsDistributionRecipient is Ownable { address public rewardsDistribution; function notifyRewardAmount(uint256 reward) virtual external; modifier onlyRewardsDistribution() { require(msg.sender == rewardsDistribution, "Caller is not RewardsDistribution contract"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardsDistribution = _rewardDistribution; } } contract GapStakingRewards is IStakingRewards, RewardsDistributionRecipient, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardsDuration = 60 days; uint256 public minStake = 10e18; uint256 public tokenRewardRatio = 100; uint256 public freezeDuration = 14 days; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public rewardsPay; uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => uint256) public initialStakeTime; constructor( address _rewardsDistribution, address _rewardsToken, address _stakingToken ) public { rewardsDistribution = _rewardsDistribution; rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return Math.min(block.timestamp, periodFinish); } // reward by token function rewardPerToken() public view override returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view override returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view override returns (uint256) { return rewardRate.mul(rewardsDuration); } function stakeOver() public view returns(uint256){ if(periodFinish < block.timestamp){ return 1; } return 0; } /* ========== MUTATIVE FUNCTIONS ========== */ function onStake(address account, uint256 balanceBeforeStake, uint256 amount) internal{ if (balanceBeforeStake < minStake && (balanceBeforeStake + amount) >= minStake) { updateRewardInt(account); } } function stake(uint256 amount) external override nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); uint256 beforeStake = _balances[msg.sender]; onStake(msg.sender, beforeStake, amount); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); if (initialStakeTime[msg.sender] == 0) { initialStakeTime[msg.sender] = block.timestamp; } emit Staked(msg.sender, amount); } function onWithdraw(address account, uint256 balanceAfterWithdraw, uint256 amount) internal{ if (balanceAfterWithdraw < minStake && (balanceAfterWithdraw + amount) >= minStake) { updateRewardInt(account); } } function withdrawBalance(uint256 amount) internal{ require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Invalid withdraw amount"); uint256 afterWithdraw = _balances[msg.sender].sub(amount); // update totalWeight base on my min stake onWithdraw(msg.sender, afterWithdraw, amount); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) { require(initialStakeTime[msg.sender].add(freezeDuration) <= block.timestamp,"Freezed, cannot withdraw"); withdrawBalance(amount); } function withdrawReward() internal{ uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); uint256 payReward = rewardsPay[msg.sender]; payReward = payReward.add(reward); rewardsPay[msg.sender] = payReward; emit RewardPaid(msg.sender, reward); } } function getReward() public override nonReentrant updateReward(msg.sender) { withdrawReward(); } function exit() external override nonReentrant updateReward(msg.sender) { require(initialStakeTime[msg.sender].add(freezeDuration) <= block.timestamp,"Freezed, cannot exit"); withdrawBalance(_balances[msg.sender]); withdrawReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { require(reward > 0, "Invalid reward amount"); rewardsToken.mint(address(this), reward); if(rewardRate == 0 || periodFinish <= block.timestamp){ rewardRate = reward.div(rewardsDuration); periodFinish = block.timestamp.add(rewardsDuration); } else{ uint256 times = reward.div(rewardRate); periodFinish = periodFinish.add(times); } lastUpdateTime = block.timestamp; emit RewardAdded(reward); } function updateRewardInt(address account) internal{ rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { updateRewardInt(account); _; } modifier onlyNotifyOne(){ require(periodFinish == 0,"Just allow notify one time!"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); }
========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) { require(reward > 0, "Invalid reward amount"); rewardsToken.mint(address(this), reward); if(rewardRate == 0 || periodFinish <= block.timestamp){ rewardRate = reward.div(rewardsDuration); periodFinish = block.timestamp.add(rewardsDuration); } else{ uint256 times = reward.div(rewardRate); periodFinish = periodFinish.add(times); } lastUpdateTime = block.timestamp; emit RewardAdded(reward); }
7,213,471
[ 1, 1432, 631, 8392, 2259, 15494, 13690, 55, 422, 1432, 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 ]
[ 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, 5066, 17631, 1060, 6275, 12, 11890, 5034, 19890, 13, 3903, 3849, 1338, 17631, 14727, 9003, 1089, 17631, 1060, 12, 2867, 12, 20, 3719, 288, 203, 3639, 2583, 12, 266, 2913, 405, 374, 16, 315, 1941, 19890, 3844, 8863, 203, 3639, 283, 6397, 1345, 18, 81, 474, 12, 2867, 12, 2211, 3631, 19890, 1769, 203, 3639, 309, 12, 266, 2913, 4727, 422, 374, 747, 3879, 11641, 1648, 1203, 18, 5508, 15329, 203, 5411, 19890, 4727, 273, 19890, 18, 2892, 12, 266, 6397, 5326, 1769, 203, 5411, 3879, 11641, 273, 1203, 18, 5508, 18, 1289, 12, 266, 6397, 5326, 1769, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 2254, 5034, 4124, 273, 19890, 18, 2892, 12, 266, 2913, 4727, 1769, 203, 5411, 3879, 11641, 273, 3879, 11641, 18, 1289, 12, 8293, 1769, 203, 3639, 289, 203, 3639, 1142, 1891, 950, 273, 1203, 18, 5508, 31, 203, 3639, 3626, 534, 359, 1060, 8602, 12, 266, 2913, 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 ]
./partial_match/1/0xAdFc8C296eb7CEc677C2DdecE28007A3D4e465a1/sources/contracts/dependencies/openzeppelin/contracts/SafeMath.sol
@notice Returns x - y, reverts if underflows @param x The minuend @param y The subtrahend @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { require((z = x - y) <= x); } }
2,890,219
[ 1, 1356, 619, 300, 677, 16, 15226, 87, 309, 3613, 24190, 225, 619, 1021, 1131, 89, 409, 225, 677, 1021, 720, 2033, 25710, 327, 998, 1021, 7114, 434, 619, 471, 677, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 720, 12, 11890, 5034, 619, 16, 2254, 5034, 677, 13, 2713, 16618, 1135, 261, 11890, 5034, 998, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2583, 12443, 94, 273, 619, 300, 677, 13, 1648, 619, 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, -100, -100, -100, -100, -100, -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.8; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./UsingRegistry.sol"; import "./interfaces/IExchange.sol"; /// @title SavingsCELO validator Group contract SavingsCELOVGroup is Ownable, UsingRegistry { using SafeMath for uint256; address public _savingsCELO; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor (address savingsCELO) public { _savingsCELO = savingsCELO; require( getAccounts().createAccount(), "createAccount failed"); getAccounts().setName("SavingsCELO - Group"); } /// Authorizes new vote signer that can manage voting for all of groups locked CELO. /// {v, r, s} constitutes proof-of-key-possession signature of signer for this /// contract address. function authorizeVoteSigner( address signer, uint8 v, bytes32 r, bytes32 s) onlyOwner external { getAccounts().authorizeVoteSigner(signer, v, r, s); } /// Authorizes new validator signer that can manage group registration/deregistration and /// group memebrs. /// {v, r, s} constitutes proof-of-key-possession signature of signer for this /// contract address. function authorizeValidatorSigner( address signer, uint8 v, bytes32 r, bytes32 s) onlyOwner external { getAccounts().authorizeValidatorSigner(signer, v, r, s); } /// Proxy function for locked CELO management. function lockGold(uint256 value) onlyOwner external { getLockedGold().lock{gas:gasleft(), value: value}(); } /// Proxy function for locked CELO management. function unlockGold(uint256 value) onlyOwner external { getLockedGold().unlock(value); } /// Proxy function for locked CELO management. function relockGold(uint256 index, uint256 value) onlyOwner external { getLockedGold().relock(index, value); } /// Proxy function for locked CELO management. function withdrawLockedGold(uint256 index) onlyOwner external { getLockedGold().withdraw(index); } /// Transfer CELO back to the owner. function withdraw(uint256 amount) onlyOwner external { require( getGoldToken().transfer(msg.sender, amount), "withdraw failed"); } /// Exchanges cUSD epoch rewards to CELO and donates it back to SavingsCELO contract. /// Anyone can call this function. Since cUSD rewards per epoch are significantly smaller /// compared to Exchange buckets, it is safe to allow anyone to call this function and /// convert cUSD -> CELO at market rate at any point. function exchangeAndDonateEpochRewards( uint256 amount, uint256 minExchangeAmount) external { IExchange _exchange = getExchange(); require( getStableToken().approve(address(_exchange), amount), "unable to approve stableToken transfer"); uint256 celoAmount = _exchange.sell(amount, minExchangeAmount, false); require( getGoldToken().transfer(_savingsCELO, celoAmount), "transfer of CELO failed"); } receive() external payable {} }
Proxy function for locked CELO management.
function withdrawLockedGold(uint256 index) onlyOwner external { getLockedGold().withdraw(index); }
945,823
[ 1, 3886, 445, 364, 8586, 29538, 1502, 11803, 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 ]
[ 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, 202, 915, 598, 9446, 8966, 43, 1673, 12, 11890, 5034, 770, 13, 1338, 5541, 3903, 288, 203, 202, 202, 588, 8966, 43, 1673, 7675, 1918, 9446, 12, 1615, 1769, 203, 202, 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, -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 // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: lost2rishore/CollectibleContract/@lib/Initializable.sol pragma solidity ^0.8.1; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: lost2rishore/CollectibleContract/@lib/EIP712Base.sol pragma solidity ^0.8.1; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: lost2rishore/CollectibleContract/@lib/NativeMetaTransaction.sol pragma solidity ^0.8.1; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: lost2rishore/CollectibleContract/@lib/ContextMixin.sol pragma solidity ^0.8.1; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: lost2rishore/CollectibleContract/@lib/Pauseable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Pause contract to help stop transactions. abstract contract Pauseable is Ownable { bool public paused = false; /** * @dev pause or resume the pledge function and the claim function * @param _state true means paused */ function pause(bool _state) external onlyOwner { paused = _state; } function _setPauseState(bool _state) internal onlyOwner { paused = _state; } } // File: lost2rishore/CollectibleContract/@lib/Priceable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Set price of tokens in contract abstract contract Priceable is Ownable { uint256 private _tokenPrice = 0; /** * @dev Internal setting price of tokens in eth * @param _etherPrice price in eth i.e 0.04 */ function _setTokenPrice(uint _etherPrice) internal onlyOwner { _tokenPrice = _etherPrice; } /** * @dev Set price of tokens in eth * @param _etherPrice price in eth i.e 0.04 */ function setTokenPrice(uint _etherPrice) external onlyOwner { _setTokenPrice(_etherPrice); } function getTokenPrice() public view returns(uint256) { return _tokenPrice; } } // File: lost2rishore/CollectibleContract/@lib/Whitelistable.sol pragma solidity ^0.8.0; /// @author nexusque /// @title Can use whitelist for varius functions abstract contract Whitelistable is Ownable { bool public whitelistRequired = true; mapping(address => bool) public whitelist; event WhitelistedAddressRemoved(address addr); event WhitelistedAddressAdded(address addr); event WhitelistedRequirementChanged(bool val); /** * @dev throws error if called by any wallet that is not whitelisted */ modifier onlyWhitelisted() { if (whitelistRequired == true) require(whitelist[msg.sender], "Alert: You're not on the whitelist."); _; } constructor( address[] memory _whitelistAddresses ) { _addAddressesToWhitelist(_whitelistAddresses); } /** * @dev Check if a wallet is whitelisted * @param _owner address */ function isWhitelisted(address _owner) external view returns (bool) { return whitelist[_owner] == true; } /** * @dev change whitelist requirement * @param _val bool */ function setWhitelistRequirement(bool _val) external onlyOwner { whitelistRequired = _val; emit WhitelistedRequirementChanged(_val); } /** * @dev add addresses to the whitelist * @param addrs addresses */ function addAddressesToWhitelist(address[] memory addrs) external onlyOwner { _addAddressesToWhitelist(addrs); } function _addAddressesToWhitelist(address[] memory addrs) internal onlyOwner { for (uint32 i = 0; i < addrs.length; i++) { whitelist[addrs[i]] = true; emit WhitelistedAddressAdded(addrs[i]); } } /** * @dev remove addresses from the whitelist * @param addrs addresses */ function removeAddressesFromWhitelist(address[] memory addrs) external onlyOwner { _removeAddressesFromWhitelist(addrs); } function _removeAddressesFromWhitelist(address[] memory addrs) internal onlyOwner { for (uint32 i = 0; i < addrs.length; i++) { _removeAddressFromWhitelist(addrs[i]); } } function _removeAddressFromWhitelist(address addrs) internal onlyOwner { whitelist[addrs] = false; emit WhitelistedAddressRemoved(addrs); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: lost2rishore/CollectibleContract/@lib/WithLimitedSupply.sol pragma solidity ^0.8.0; /// @author 1001.digital /// ReviewedBy nexusque /// @title A token tracker that limits the token supply and increments token IDs on each new mint. abstract contract WithLimitedSupply is ERC721Enumerable { using Counters for Counters.Counter; // Keeps track of how many we have minted Counters.Counter private _tokenCount; /// @dev The maximum count of tokens this token tracker will hold. uint256 private _totalSupply; /// Instanciate the contract /// @param totalSupply_ how many tokens this collection should hold constructor (uint256 totalSupply_) { _totalSupply = totalSupply_; } /// @dev Get the max Supply /// @return the maximum token count function totalSupply() public override view returns (uint256) { return _totalSupply; } /// @dev Get the current token count /// @return the created token count function tokenCount() public view returns (uint256) { return _tokenCount.current(); } /// @dev Check whether tokens are still available /// @return the available token count function availableTokenCount() public view returns (uint256) { return totalSupply() - tokenCount(); } /// @dev Increment the token count and fetch the latest count /// @return the next token id function nextToken() internal virtual ensureAvailability returns (uint256) { uint256 token = _tokenCount.current(); _tokenCount.increment(); return token; } /// @dev Check whether another token is still available modifier ensureAvailability() { require(availableTokenCount() > 0, "No more tokens available"); _; } /// @param amount Check whether number of tokens are still available /// @dev Check whether tokens are still available modifier ensureAvailabilityFor(uint256 amount) { require(availableTokenCount() >= amount, "Requested number of tokens not available"); _; } } // File: lost2rishore/CollectibleContract/Collectible.sol pragma solidity ^0.8.2; /// @author nexusque contract LostTRIShore is ContextMixin, NativeMetaTransaction, Ownable, Whitelistable, Priceable, Pauseable, WithLimitedSupply { using SafeMath for uint256; address payable public clientAddress; address payable public artistAddress; address payable public paymentAddress; string public baseTokenURI = ""; string public baseExtension = ".json"; uint256 private _maxSupply = 10000; uint8 private _chapters = 5; // For RandomlyAssigned: Max supply is 1000; id start from 1 (instead of 0) constructor( string memory _name, string memory _symbol, string memory _uri, address _artistAddress, address _clientAddress, address _paymentAddress, address[] memory _whitelistAddresses ) ERC721 (_name, _symbol) Whitelistable(_whitelistAddresses) WithLimitedSupply(_maxSupply) { _initializeEIP712(_name); baseTokenURI = _uri; // ~$20 USD as of 04/08/2022 _setTokenPrice(0.006 ether); artistAddress = payable(_artistAddress); clientAddress = payable(_clientAddress); paymentAddress = payable(_paymentAddress); } function claim() external onlyWhitelisted { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(1); _removeAddressFromWhitelist(msg.sender); } function mint() external payable { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= getTokenPrice(), "Alert: You need to pay at least the required cost." ); _mintList(1); } function mintTotalOf(uint8 _num) external payable { require(!paused, "Contract is paused"); require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= (getTokenPrice() * uint256(_num)), "Alert: You need to pay at least the required cost." ); _mintList(_num); } function ownerMintTotalOf(uint8 _num) external onlyOwner { require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(_num); } /** * @dev Airdrop tokens to the following addresses * @param _addresses list of addresses to airdrop to */ function airDropToAdresses(address[] memory _addresses) external onlyOwner { for (uint32 i = 0; i < _addresses.length; i++) { if (tokenCount() + 1 <= _maxSupply) { _safeMint(_addresses[i], nextToken()); } } _removeAddressesFromWhitelist(_addresses); } /** * @dev mint _num of * @param _num Quantity to mint */ function _mintList(uint8 _num) private { for (uint8 i = 0; i < _num; i++) { _safeMint(msg.sender, nextToken()); } // Pause after each chapter sells out if (tokenCount() % (_maxSupply / _chapters) == 0) { _setPauseState(true); } } /** * @dev change the baseTokenURI (only Owner) * @param _baseTokenURI base token URI */ function setBaseURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } /** * @dev change the setPaymentAddress (only Owner) * @param _paymentAddress address to send eth to when withdrawing */ function setPaymentAddress(address _paymentAddress) external onlyOwner { paymentAddress = payable(_paymentAddress); } /** * @dev returns the token URI of _tokenId * @param _tokenId id of the token */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Alert: This token does not exist!"); return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId), baseExtension)); } /** * @dev this is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } /** * @dev set the base extension of the metadata file (only Owner) * @param _newBaseExtension extension (empty or with a dot infront) */ function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } /** * @dev get the ids of the Humans owned by _owner * @param _owner address */ function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } /** * @dev withdraw all balance of this contract to the paymentAddress contract */ function withdraw() external payable onlyOwner { (bool success, ) = payable(paymentAddress).call{value: address(this).balance}(""); require(success, "Transfer failed."); } }
@author nexusque For RandomlyAssigned: Max supply is 1000; id start from 1 (instead of 0)
contract LostTRIShore is ContextMixin, NativeMetaTransaction, Ownable, Whitelistable, Priceable, Pauseable, WithLimitedSupply { using SafeMath for uint256; address payable public clientAddress; address payable public artistAddress; address payable public paymentAddress; string public baseTokenURI = ""; string public baseExtension = ".json"; uint256 private _maxSupply = 10000; uint8 private _chapters = 5; constructor( string memory _name, string memory _symbol, string memory _uri, address _artistAddress, address _clientAddress, address _paymentAddress, address[] memory _whitelistAddresses ) ERC721 (_name, _symbol) Whitelistable(_whitelistAddresses) WithLimitedSupply(_maxSupply) { _initializeEIP712(_name); baseTokenURI = _uri; _setTokenPrice(0.006 ether); artistAddress = payable(_artistAddress); clientAddress = payable(_clientAddress); paymentAddress = payable(_paymentAddress); } function claim() external onlyWhitelisted { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(1); _removeAddressFromWhitelist(msg.sender); } function mint() external payable { require(!paused, "Contract is paused"); require( tokenCount() + 1 <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= getTokenPrice(), "Alert: You need to pay at least the required cost." ); _mintList(1); } function mintTotalOf(uint8 _num) external payable { require(!paused, "Contract is paused"); require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); require( msg.value >= (getTokenPrice() * uint256(_num)), "Alert: You need to pay at least the required cost." ); _mintList(_num); } function ownerMintTotalOf(uint8 _num) external onlyOwner { require( tokenCount() + uint256(_num) <= _maxSupply, "Alert: Sorry not enough tokens left" ); _mintList(_num); } function airDropToAdresses(address[] memory _addresses) external onlyOwner { for (uint32 i = 0; i < _addresses.length; i++) { if (tokenCount() + 1 <= _maxSupply) { _safeMint(_addresses[i], nextToken()); } } _removeAddressesFromWhitelist(_addresses); } function airDropToAdresses(address[] memory _addresses) external onlyOwner { for (uint32 i = 0; i < _addresses.length; i++) { if (tokenCount() + 1 <= _maxSupply) { _safeMint(_addresses[i], nextToken()); } } _removeAddressesFromWhitelist(_addresses); } function airDropToAdresses(address[] memory _addresses) external onlyOwner { for (uint32 i = 0; i < _addresses.length; i++) { if (tokenCount() + 1 <= _maxSupply) { _safeMint(_addresses[i], nextToken()); } } _removeAddressesFromWhitelist(_addresses); } function _mintList(uint8 _num) private { for (uint8 i = 0; i < _num; i++) { _safeMint(msg.sender, nextToken()); } if (tokenCount() % (_maxSupply / _chapters) == 0) { _setPauseState(true); } } function _mintList(uint8 _num) private { for (uint8 i = 0; i < _num; i++) { _safeMint(msg.sender, nextToken()); } if (tokenCount() % (_maxSupply / _chapters) == 0) { _setPauseState(true); } } function _mintList(uint8 _num) private { for (uint8 i = 0; i < _num; i++) { _safeMint(msg.sender, nextToken()); } if (tokenCount() % (_maxSupply / _chapters) == 0) { _setPauseState(true); } } function setBaseURI(string memory _baseTokenURI) external onlyOwner { baseTokenURI = _baseTokenURI; } function setPaymentAddress(address _paymentAddress) external onlyOwner { paymentAddress = payable(_paymentAddress); } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Alert: This token does not exist!"); return string(abi.encodePacked(baseTokenURI, Strings.toString(_tokenId), baseExtension)); } function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function withdraw() external payable onlyOwner { require(success, "Transfer failed."); } (bool success, ) = payable(paymentAddress).call{value: address(this).balance}(""); }
498,097
[ 1, 82, 21029, 1857, 2457, 8072, 715, 20363, 30, 4238, 14467, 353, 4336, 31, 612, 787, 628, 404, 261, 8591, 684, 434, 374, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 669, 6566, 1555, 479, 353, 225, 1772, 14439, 16, 225, 16717, 2781, 3342, 16, 14223, 6914, 16, 3497, 7523, 429, 16, 20137, 429, 16, 31357, 429, 16, 3423, 3039, 329, 3088, 1283, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1758, 8843, 429, 1071, 1004, 1887, 31, 203, 565, 1758, 8843, 429, 1071, 15469, 1887, 31, 203, 565, 1758, 8843, 429, 1071, 5184, 1887, 31, 203, 203, 565, 533, 1071, 1026, 1345, 3098, 273, 1408, 31, 203, 565, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 203, 565, 2254, 5034, 3238, 389, 1896, 3088, 1283, 273, 12619, 31, 203, 565, 2254, 28, 3238, 389, 343, 1657, 414, 273, 1381, 31, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 533, 3778, 389, 1650, 16, 203, 3639, 1758, 389, 25737, 1887, 16, 203, 3639, 1758, 389, 2625, 1887, 16, 203, 3639, 1758, 389, 9261, 1887, 16, 203, 3639, 1758, 8526, 3778, 389, 20409, 7148, 203, 203, 565, 262, 4232, 39, 27, 5340, 261, 67, 529, 16, 389, 7175, 13, 3497, 7523, 429, 24899, 20409, 7148, 13, 3423, 3039, 329, 3088, 1283, 24899, 1896, 3088, 1283, 13, 288, 203, 3639, 389, 11160, 41, 2579, 27, 2138, 24899, 529, 1769, 203, 1377, 203, 3639, 1026, 1345, 3098, 273, 389, 1650, 31, 203, 203, 3639, 389, 542, 1345, 5147, 12, 20, 18, 713, 26, 225, 2437, 1769, 203, 203, 3639, 15469, 1887, 273, 8843, 429, 24899, 25737, 1887, 2 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol"; import "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol"; import "@uniswap/v3-periphery/contracts/base/LiquidityManagement.sol"; contract LiquidityExamples is IERC721Receiver, LiquidityManagement { address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; uint24 public constant poolFee = 3000; INonfungiblePositionManager public immutable nonfungiblePositionManager; struct Deposit { address owner; uint128 liquidity; address token0; address token1; } mapping(uint256 => Deposit) public deposits; constructor( INonfungiblePositionManager _nonfungiblePositionManager, address _factory, address _WETH9 ) PeripheryImmutableState(_factory, _WETH9) { nonfungiblePositionManager = _nonfungiblePositionManager; } function onERC721Received( address operator, address, uint256 tokenId, bytes calldata ) external override returns (bytes4) { // get position information _createDeposit(operator, tokenId); return this.onERC721Received.selector; } function _createDeposit(address owner, uint256 tokenId) internal { ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(tokenId); // set the owner and data for position // operator is msg.sender deposits[tokenId] = Deposit({ owner: owner, liquidity: liquidity, token0: token0, token1: token1 }); } /// @notice Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity /// @return tokenId The id of the newly minted ERC721 /// @return liquidity The amount of liquidity for the position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) { // For this example, we will provide equal amounts of liquidity in both assets. // Providing liquidity in both assets means liquidity will be earning fees and is considered in-range. uint256 amount0ToMint = 1000; uint256 amount1ToMint = 1000; // Approve the position manager TransferHelper.safeApprove( DAI, address(nonfungiblePositionManager), amount0ToMint ); TransferHelper.safeApprove( USDC, address(nonfungiblePositionManager), amount1ToMint ); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams({ token0: DAI, token1: USDC, fee: poolFee, tickLower: TickMath.MIN_TICK, tickUpper: TickMath.MAX_TICK, amount0Desired: amount0ToMint, amount1Desired: amount1ToMint, amount0Min: 0, amount1Min: 0, recipient: address(this), deadline: block.timestamp }); // Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager .mint(params); // Create a deposit _createDeposit(msg.sender, tokenId); // Remove allowance and refund in both assets. if (amount0 < amount0ToMint) { TransferHelper.safeApprove( DAI, address(nonfungiblePositionManager), 0 ); uint256 refund0 = amount0ToMint - amount0; TransferHelper.safeTransfer(DAI, msg.sender, refund0); } if (amount1 < amount1ToMint) { TransferHelper.safeApprove( USDC, address(nonfungiblePositionManager), 0 ); uint256 refund1 = amount1ToMint - amount1; TransferHelper.safeTransfer(USDC, msg.sender, refund1); } } /// @notice Collects the fees associated with provided liquidity /// @dev The contract must hold the erc721 token before it can collect fees /// @param tokenId The id of the erc721 token /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { // Caller must own the ERC721 position // Call to safeTransfer will trigger `onERC721Received` which must return the selector else transfer will fail nonfungiblePositionManager.safeTransferFrom( msg.sender, address(this), tokenId ); // set amount0Max and amount1Max to uint256.max to collect all fees // alternatively can set recipient to msg.sender and avoid another transaction in `sendToOwner` INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = nonfungiblePositionManager.collect(params); // send collected feed back to owner _sendToOwner(tokenId, amount0, amount1); } /// @notice Transfers funds to owner of NFT /// @param tokenId The id of the erc721 /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 function _sendToOwner( uint256 tokenId, uint256 amount0, uint256 amount1 ) internal { // get owner of contract address owner = deposits[tokenId].owner; address token0 = deposits[tokenId].token0; address token1 = deposits[tokenId].token1; // send collected fees to owner TransferHelper.safeTransfer(token0, owner, amount0); TransferHelper.safeTransfer(token1, owner, amount1); } /// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery. /// @param tokenId The id of the erc721 token /// @return amount0 The amount received back in token0 /// @return amount1 The amount returned back in token1 function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { // caller must be the owner of the NFT require(msg.sender == deposits[tokenId].owner, "Not the owner"); // get liquidity data for tokenId uint128 liquidity = deposits[tokenId].liquidity; uint128 halfLiquidity = liquidity / 2; // amount0Min and amount1Min are price slippage checks // if the amount received after burning is not greater than these minimums, transaction will fail INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: tokenId, liquidity: halfLiquidity, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity( params ); //send liquidity back to owner _sendToOwner(tokenId, amount0, amount1); } /// @notice Increases liquidity in the current range /// @dev Pool must be initialized already to add liquidity /// @param tokenId The id of the erc721 token /// @param amount0 The amount to add of token0 /// @param amount1 The amount to add of token1 function increaseLiquidityCurrentRange( uint256 tokenId, uint256 amountAdd0, uint256 amountAdd1 ) external returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { INonfungiblePositionManager.IncreaseLiquidityParams memory params = INonfungiblePositionManager .IncreaseLiquidityParams({ tokenId: tokenId, amount0Desired: amountAdd0, amount1Desired: amountAdd1, amount0Min: 0, amount1Min: 0, deadline: block.timestamp }); (liquidity, amount0, amount1) = nonfungiblePositionManager .increaseLiquidity(params); } }
@notice Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity @return tokenId The id of the newly minted ERC721 @return liquidity The amount of liquidity for the position @return amount0 The amount of token0 @return amount1 The amount of token1 For this example, we will provide equal amounts of liquidity in both assets. Providing liquidity in both assets means liquidity will be earning fees and is considered in-range. Approve the position manager Remove allowance and refund in both assets.
function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) { uint256 amount0ToMint = 1000; uint256 amount1ToMint = 1000; TransferHelper.safeApprove( DAI, address(nonfungiblePositionManager), amount0ToMint ); TransferHelper.safeApprove( USDC, address(nonfungiblePositionManager), amount1ToMint ); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager.MintParams({ token0: DAI, token1: USDC, fee: poolFee, tickLower: TickMath.MIN_TICK, tickUpper: TickMath.MAX_TICK, amount0Desired: amount0ToMint, amount1Desired: amount1ToMint, amount0Min: 0, amount1Min: 0, recipient: address(this), deadline: block.timestamp }); .mint(params); if (amount0 < amount0ToMint) { TransferHelper.safeApprove( DAI, address(nonfungiblePositionManager), 0 ); uint256 refund0 = amount0ToMint - amount0; TransferHelper.safeTransfer(DAI, msg.sender, refund0); } if (amount1 < amount1ToMint) { TransferHelper.safeApprove( USDC, address(nonfungiblePositionManager), 0 ); uint256 refund1 = amount1ToMint - amount1; TransferHelper.safeTransfer(USDC, msg.sender, refund1); } }
12,748,433
[ 1, 10125, 326, 312, 474, 445, 2553, 316, 1534, 16045, 627, 16, 312, 28142, 326, 1967, 3844, 434, 1517, 1147, 18, 2457, 333, 3454, 732, 854, 17721, 4336, 463, 18194, 471, 4336, 11836, 5528, 316, 4501, 372, 24237, 327, 1147, 548, 1021, 612, 434, 326, 10894, 312, 474, 329, 4232, 39, 27, 5340, 327, 4501, 372, 24237, 1021, 3844, 434, 4501, 372, 24237, 364, 326, 1754, 327, 3844, 20, 1021, 3844, 434, 1147, 20, 327, 3844, 21, 1021, 3844, 434, 1147, 21, 2457, 333, 3454, 16, 732, 903, 5615, 3959, 30980, 434, 4501, 372, 24237, 316, 3937, 7176, 18, 1186, 1246, 310, 4501, 372, 24237, 316, 3937, 7176, 4696, 4501, 372, 24237, 903, 506, 425, 9542, 1656, 281, 471, 353, 7399, 316, 17, 3676, 18, 1716, 685, 537, 326, 1754, 3301, 3581, 1699, 1359, 471, 16255, 316, 3937, 7176, 18, 2, 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, 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 ]
[ 1, 565, 445, 312, 474, 1908, 2555, 1435, 203, 3639, 3903, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 1147, 548, 16, 203, 5411, 2254, 10392, 4501, 372, 24237, 16, 203, 5411, 2254, 5034, 3844, 20, 16, 203, 5411, 2254, 5034, 3844, 21, 203, 3639, 262, 203, 565, 288, 203, 3639, 2254, 5034, 3844, 20, 774, 49, 474, 273, 4336, 31, 203, 3639, 2254, 5034, 3844, 21, 774, 49, 474, 273, 4336, 31, 203, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 203, 5411, 463, 18194, 16, 203, 5411, 1758, 12, 5836, 12125, 75, 1523, 2555, 1318, 3631, 203, 5411, 3844, 20, 774, 49, 474, 203, 3639, 11272, 203, 3639, 12279, 2276, 18, 4626, 12053, 537, 12, 203, 5411, 11836, 5528, 16, 203, 5411, 1758, 12, 5836, 12125, 75, 1523, 2555, 1318, 3631, 203, 5411, 3844, 21, 774, 49, 474, 203, 3639, 11272, 203, 203, 3639, 2120, 265, 12125, 75, 1523, 2555, 1318, 18, 49, 474, 1370, 203, 5411, 3778, 859, 273, 2120, 265, 12125, 75, 1523, 2555, 1318, 18, 49, 474, 1370, 12590, 203, 7734, 1147, 20, 30, 463, 18194, 16, 203, 7734, 1147, 21, 30, 11836, 5528, 16, 203, 7734, 14036, 30, 2845, 14667, 16, 203, 7734, 4024, 4070, 30, 13588, 10477, 18, 6236, 67, 56, 16656, 16, 203, 7734, 4024, 5988, 30, 13588, 10477, 18, 6694, 67, 56, 16656, 16, 203, 7734, 3844, 20, 25683, 30, 3844, 20, 774, 49, 474, 16, 203, 7734, 3844, 21, 25683, 30, 3844, 21, 774, 49, 474, 16, 203, 7734, 3844, 20, 2930, 30, 374, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../contracts/ActiveBridgeSetBlockRelay.sol"; /** * @title Test Helper for the new block Relay contract * @dev The aim of this contract is to raise the visibility modifier of new block relay contract functions for testing purposes * @author Witnet Foundation */ contract ABSBlockRelayTestHelper is ActiveBridgeSetBlockRelay { ActiveBridgeSetBlockRelay public br; uint256 public timestamp; constructor ( uint256 _witnetGenesis, uint256 _epochSeconds, uint256 _firstBlock, address _wbiAddress) public ActiveBridgeSetBlockRelay(_witnetGenesis, _epochSeconds, _firstBlock, _wbiAddress) {} // Sets the current epoch to be the next function nextEpoch() external { currentEpoch = currentEpoch + 1; } // Sets the currentEpoch function setEpoch(uint256 _epoch) external { currentEpoch = _epoch; } // Gets the vote with the poposeBlock inputs function getVote( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) external pure returns(uint256) { uint256 vote = uint256( sha256( abi.encodePacked( _blockHash, _epoch, _drMerkleRoot, _tallyMerkleRoot, _previousVote))); return vote; } // Gets the blockHash of a vote finalized in a specific epoch function getBlockHash(uint256 _epoch) external view returns (uint256) { uint256 blockHash = epochFinalizedBlock[_epoch]; return blockHash; } // Gets the length of the candidates array function getCandidatesLength() external view returns (uint256) { return candidates.length; } // Checks if the epoch is finalized function checkEpochFinalized(uint256 _epoch) external view returns (bool) { if (epochFinalizedBlock[_epoch] != 0) { return true; } } // Updates the currentEpoch function updateEpoch() public view override returns (uint256) { return currentEpoch; } }
Gets the vote with the poposeBlock inputs
function getVote( uint256 _blockHash, uint256 _epoch, uint256 _drMerkleRoot, uint256 _tallyMerkleRoot, uint256 _previousVote) external pure returns(uint256) { uint256 vote = uint256( sha256( abi.encodePacked( _blockHash, _epoch, _drMerkleRoot, _tallyMerkleRoot, _previousVote))); return vote; }
5,430,838
[ 1, 3002, 326, 12501, 598, 326, 1843, 2584, 1768, 4540, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11031, 1168, 12, 203, 565, 2254, 5034, 389, 2629, 2310, 16, 203, 565, 2254, 5034, 389, 12015, 16, 203, 565, 2254, 5034, 389, 3069, 8478, 15609, 2375, 16, 203, 565, 2254, 5034, 389, 88, 1230, 8478, 15609, 2375, 16, 203, 565, 2254, 5034, 389, 11515, 19338, 13, 3903, 16618, 1135, 12, 11890, 5034, 13, 203, 565, 288, 203, 565, 2254, 5034, 12501, 273, 2254, 5034, 12, 203, 1377, 6056, 5034, 12, 203, 3639, 24126, 18, 3015, 4420, 329, 12, 203, 1377, 389, 2629, 2310, 16, 203, 1377, 389, 12015, 16, 203, 1377, 389, 3069, 8478, 15609, 2375, 16, 203, 1377, 389, 88, 1230, 8478, 15609, 2375, 16, 203, 1377, 389, 11515, 19338, 3719, 1769, 203, 203, 565, 327, 12501, 31, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-23 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File contracts/forwarder/IRelayRecipient.sol // SPDX-License-Identifier:MIT pragma solidity ^0.7.6; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public view virtual returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view virtual returns (address payable); function versionRecipient() external view virtual returns (string memory); } // File contracts/forwarder/BaseRelayRecipient.sol pragma solidity ^0.7.6; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; /* * require a function to be called through GSN only */ modifier trustedForwarderOnly() { require( msg.sender == address(trustedForwarder), "Function can only be called through the trusted Forwarder" ); _; } function isTrustedForwarder(address forwarder) public view override returns (bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view virtual override returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return msg.sender; } } } // File contracts/abstract/Pausable.sol pragma solidity >=0.6.0 <=0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is BaseRelayRecipient { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File contracts/abstract/Ownable.sol pragma solidity >=0.6.0 <=0.8.0; abstract contract Ownable is Pausable { address public _owner; address public _admin; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor(address ownerAddress) { _owner = _msgSender(); _admin = ownerAddress; emit OwnershipTransferred(address(0), _owner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(_admin == _msgSender(), "Ownable: caller is not the Admin"); _; } /** * @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 onlyAdmin { emit OwnershipTransferred(_owner, _admin); _owner = _admin; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/libraries/SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/interfaces/IERC20.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/abstract/Admin.sol pragma solidity ^0.7.0; abstract contract Admin is Ownable { struct tokenInfo { bool isExist; uint8 decimal; uint256 userMinStake; uint256 userMaxStake; uint256 totalMaxStake; uint256 lockableDays; bool optionableStatus; } using SafeMath for uint256; address[] public tokens; mapping(address => address[]) public tokensSequenceList; mapping(address => tokenInfo) public tokenDetails; mapping(address => uint256) public rewardCap; mapping(address => mapping(address => uint256)) public tokenDailyDistribution; mapping(address => mapping(address => bool)) public tokenBlockedStatus; uint256[] public intervalDays = [1, 8, 15, 22, 29, 36]; uint256 public constant DAYS = 1 days; uint256 public constant HOURS = 1 hours; uint256 public stakeDuration; uint256 public refPercentage; uint256 public optionableBenefit; event TokenDetails( address indexed tokenAddress, uint256 userMinStake, uint256 userMaxStake, uint256 totalMaxStake, uint256 updatedTime ); event LockableTokenDetails( address indexed tokenAddress, uint256 lockableDys, bool optionalbleStatus, uint256 updatedTime ); event DailyDistributionDetails( address indexed stakedTokenAddress, address indexed rewardTokenAddress, uint256 rewards, uint256 time ); event SequenceDetails( address indexed stakedTokenAddress, address[] rewardTokenSequence, uint256 time ); event StakeDurationDetails(uint256 updatedDuration, uint256 time); event OptionableBenefitDetails(uint256 updatedBenefit, uint256 time); event ReferrerPercentageDetails(uint256 updatedRefPercentage, uint256 time); event IntervalDaysDetails(uint256[] updatedIntervals, uint256 time); event BlockedDetails( address indexed stakedTokenAddress, address indexed rewardTokenAddress, bool blockedStatus, uint256 time ); event WithdrawDetails( address indexed tokenAddress, uint256 withdrawalAmount, uint256 time ); constructor(address _owner) Ownable(_owner) { stakeDuration = 90 days; refPercentage = 2500000000000000000; optionableBenefit = 2; } function addToken( address tokenAddress, uint256 userMinStake, uint256 userMaxStake, uint256 totalStake, uint8 decimal ) public onlyOwner returns (bool) { if (!(tokenDetails[tokenAddress].isExist)) tokens.push(tokenAddress); tokenDetails[tokenAddress].isExist = true; tokenDetails[tokenAddress].decimal = decimal; tokenDetails[tokenAddress].userMinStake = userMinStake; tokenDetails[tokenAddress].userMaxStake = userMaxStake; tokenDetails[tokenAddress].totalMaxStake = totalStake; emit TokenDetails( tokenAddress, userMinStake, userMaxStake, totalStake, block.timestamp ); return true; } function setDailyDistribution( address[] memory stakedToken, address[] memory rewardToken, uint256[] memory dailyDistribution ) public onlyOwner { require( stakedToken.length == rewardToken.length && rewardToken.length == dailyDistribution.length, "Invalid Input" ); for (uint8 i = 0; i < stakedToken.length; i++) { require( tokenDetails[stakedToken[i]].isExist && tokenDetails[rewardToken[i]].isExist, "Token not exist" ); tokenDailyDistribution[stakedToken[i]][ rewardToken[i] ] = dailyDistribution[i]; emit DailyDistributionDetails( stakedToken[i], rewardToken[i], dailyDistribution[i], block.timestamp ); } } function updateSequence( address stakedToken, address[] memory rewardTokenSequence ) public onlyOwner { tokensSequenceList[stakedToken] = new address[](0); require(tokenDetails[stakedToken].isExist, "Staked Token Not Exist"); for (uint8 i = 0; i < rewardTokenSequence.length; i++) { require(rewardTokenSequence.length <= tokens.length, "Invalid Input"); require( tokenDetails[rewardTokenSequence[i]].isExist, "Reward Token Not Exist" ); tokensSequenceList[stakedToken].push(rewardTokenSequence[i]); } emit SequenceDetails( stakedToken, tokensSequenceList[stakedToken], block.timestamp ); } function updateToken( address tokenAddress, uint256 userMinStake, uint256 userMaxStake, uint256 totalStake ) public onlyOwner { require(tokenDetails[tokenAddress].isExist, "Token Not Exist"); tokenDetails[tokenAddress].userMinStake = userMinStake; tokenDetails[tokenAddress].userMaxStake = userMaxStake; tokenDetails[tokenAddress].totalMaxStake = totalStake; emit TokenDetails( tokenAddress, userMinStake, userMaxStake, totalStake, block.timestamp ); } function lockableToken( address tokenAddress, uint8 lockableStatus, uint256 lockedDays, bool optionableStatus ) public onlyOwner { require( lockableStatus == 1 || lockableStatus == 2 || lockableStatus == 3, "Invalid Lockable Status" ); require(tokenDetails[tokenAddress].isExist == true, "Token Not Exist"); if (lockableStatus == 1) { tokenDetails[tokenAddress].lockableDays = block.timestamp.add(lockedDays); } else if (lockableStatus == 2) tokenDetails[tokenAddress].lockableDays = 0; else if (lockableStatus == 3) tokenDetails[tokenAddress].optionableStatus = optionableStatus; emit LockableTokenDetails( tokenAddress, tokenDetails[tokenAddress].lockableDays, tokenDetails[tokenAddress].optionableStatus, block.timestamp ); } function updateStakeDuration(uint256 durationTime) public onlyOwner { stakeDuration = durationTime; emit StakeDurationDetails(stakeDuration, block.timestamp); } function updateOptionableBenefit(uint256 benefit) public onlyOwner { optionableBenefit = benefit; emit OptionableBenefitDetails(optionableBenefit, block.timestamp); } function updateRefPercentage(uint256 refPer) public onlyOwner { refPercentage = refPer; emit ReferrerPercentageDetails(refPercentage, block.timestamp); } function updateIntervalDays(uint256[] memory _interval) public onlyOwner { intervalDays = new uint256[](0); for (uint8 i = 0; i < _interval.length; i++) { uint256 noD = stakeDuration.div(DAYS); require(noD > _interval[i], "Invalid Interval Day"); intervalDays.push(_interval[i]); } emit IntervalDaysDetails(intervalDays, block.timestamp); } function changeTokenBlockedStatus( address stakedToken, address rewardToken, bool status ) public onlyOwner { require( tokenDetails[stakedToken].isExist && tokenDetails[rewardToken].isExist, "Token not exist" ); tokenBlockedStatus[stakedToken][rewardToken] = status; emit BlockedDetails( stakedToken, rewardToken, tokenBlockedStatus[stakedToken][rewardToken], block.timestamp ); } function safeWithdraw(address tokenAddress, uint256 amount) public onlyOwner { require( IERC20(tokenAddress).balanceOf(address(this)) >= amount, "Insufficient Balance" ); require(IERC20(tokenAddress).transfer(_owner, amount), "Transfer failed"); emit WithdrawDetails(tokenAddress, amount, block.timestamp); } function viewTokensCount() external view returns (uint256) { return tokens.length; } function setRewardCap( address[] memory tokenAddresses, uint256[] memory rewards ) external onlyOwner returns (bool) { require(tokenAddresses.length == rewards.length, "Invalid elements"); for (uint8 v = 0; v < tokenAddresses.length; v++) { require(tokenDetails[tokenAddresses[v]].isExist, "Token is not exist"); require(rewards[v] > 0, "Invalid Reward Amount"); rewardCap[tokenAddresses[v]] = rewards[v]; } return true; } } // File contracts/UnifarmV18.sol pragma solidity ^0.7.6; /** * @title Unifarm Contract * @author OroPocket */ contract UnifarmV18 is Admin { // Wrappers over Solidity's arithmetic operations using SafeMath for uint256; // Stores Stake Details struct stakeInfo { address user; bool[] isActive; address[] referrer; address[] tokenAddress; uint256[] stakeId; uint256[] stakedAmount; uint256[] startTime; } // Mapping mapping(address => stakeInfo) public stakingDetails; mapping(address => mapping(address => uint256)) public userTotalStaking; mapping(address => uint256) public totalStaking; uint256 public poolStartTime; // Events event Stake( address indexed userAddress, uint256 stakeId, address indexed referrerAddress, address indexed tokenAddress, uint256 stakedAmount, uint256 time ); event Claim( address indexed userAddress, address indexed stakedTokenAddress, address indexed tokenAddress, uint256 claimRewards, uint256 time ); event UnStake( address indexed userAddress, address indexed unStakedtokenAddress, uint256 unStakedAmount, uint256 time, uint256 stakeId ); event ReferralEarn( address indexed userAddress, address indexed callerAddress, address indexed rewardTokenAddress, uint256 rewardAmount, uint256 time ); constructor(address _trustedForwarder) Admin(_msgSender()) { poolStartTime = block.timestamp; trustedForwarder = _trustedForwarder; } /** * @notice Stake tokens to earn rewards * @param tokenAddress Staking token address * @param amount Amount of tokens to be staked */ function stake( address referrerAddress, address tokenAddress, uint256 amount ) external whenNotPaused { // checks require(_msgSender() != referrerAddress, "STAKE: invalid referrer address"); require(tokenDetails[tokenAddress].isExist, "STAKE : Token is not Exist"); require( userTotalStaking[_msgSender()][tokenAddress].add(amount) >= tokenDetails[tokenAddress].userMinStake, "STAKE : Min Amount should be within permit" ); require( userTotalStaking[_msgSender()][tokenAddress].add(amount) <= tokenDetails[tokenAddress].userMaxStake, "STAKE : Max Amount should be within permit" ); require( totalStaking[tokenAddress].add(amount) <= tokenDetails[tokenAddress].totalMaxStake, "STAKE : Maxlimit exceeds" ); require( poolStartTime.add(stakeDuration) > block.timestamp, "STAKE: Staking Time Completed" ); // Storing stake details stakingDetails[_msgSender()].stakeId.push( stakingDetails[_msgSender()].stakeId.length ); stakingDetails[_msgSender()].isActive.push(true); stakingDetails[_msgSender()].user = _msgSender(); stakingDetails[_msgSender()].referrer.push(referrerAddress); stakingDetails[_msgSender()].tokenAddress.push(tokenAddress); stakingDetails[_msgSender()].startTime.push(block.timestamp); // Update total staking amount stakingDetails[_msgSender()].stakedAmount.push(amount); totalStaking[tokenAddress] = totalStaking[tokenAddress].add(amount); userTotalStaking[_msgSender()][tokenAddress] = userTotalStaking[ _msgSender() ][tokenAddress] .add(amount); // Transfer tokens from userf to contract require( IERC20(tokenAddress).transferFrom(_msgSender(), address(this), amount), "Transfer Failed" ); // Emit state changes emit Stake( _msgSender(), (stakingDetails[_msgSender()].stakeId.length.sub(1)), referrerAddress, tokenAddress, amount, block.timestamp ); } /** * @notice Claim accumulated rewards * @param stakeId Stake ID of the user * @param stakedAmount Staked amount of the user */ function claimRewards( address userAddress, uint256 stakeId, uint256 stakedAmount, uint256 totalStake ) internal { // Local variables uint256 interval; uint256 endOfProfit; interval = poolStartTime.add(stakeDuration); // Interval calculation if (interval > block.timestamp) endOfProfit = block.timestamp; else endOfProfit = poolStartTime.add(stakeDuration); interval = endOfProfit.sub(stakingDetails[userAddress].startTime[stakeId]); uint256[2] memory stakeData; stakeData[0] = (stakedAmount); stakeData[1] = (totalStake); // Reward calculation if (interval >= HOURS) _rewardCalculation(userAddress, stakeId, stakeData, interval); } function _rewardCalculation( address userAddress, uint256 stakeId, uint256[2] memory stakingData, uint256 interval ) internal { uint256 rewardsEarned; uint256 refEarned; uint256[2] memory noOfDays; noOfDays[1] = interval.div(HOURS); noOfDays[0] = interval.div(DAYS); rewardsEarned = noOfDays[1].mul( getOneDayReward( stakingData[0], stakingDetails[userAddress].tokenAddress[stakeId], stakingDetails[userAddress].tokenAddress[stakeId], stakingData[1] ) ); // Referrer Earning if (stakingDetails[userAddress].referrer[stakeId] != address(0)) { refEarned = (rewardsEarned.mul(refPercentage)).div(100 ether); rewardsEarned = rewardsEarned.sub(refEarned); require( IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer( stakingDetails[userAddress].referrer[stakeId], refEarned ) == true, "Transfer Failed" ); emit ReferralEarn( stakingDetails[userAddress].referrer[stakeId], _msgSender(), stakingDetails[userAddress].tokenAddress[stakeId], refEarned, block.timestamp ); } // Rewards Send sendToken( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], stakingDetails[userAddress].tokenAddress[stakeId], rewardsEarned ); uint8 i = 1; while (i < intervalDays.length) { if (noOfDays[0] >= intervalDays[i]) { uint256 reductionHours = (intervalDays[i].sub(1)).mul(24); uint256 balHours = noOfDays[1].sub(reductionHours); address rewardToken = tokensSequenceList[stakingDetails[userAddress].tokenAddress[stakeId]][ i ]; if ( rewardToken != stakingDetails[userAddress].tokenAddress[stakeId] && tokenBlockedStatus[stakingDetails[userAddress].tokenAddress[stakeId]][ rewardToken ] == false ) { rewardsEarned = balHours.mul( getOneDayReward( stakingData[0], stakingDetails[userAddress].tokenAddress[stakeId], rewardToken, stakingData[1] ) ); // Referrer Earning if (stakingDetails[userAddress].referrer[stakeId] != address(0)) { refEarned = (rewardsEarned.mul(refPercentage)).div(100 ether); rewardsEarned = rewardsEarned.sub(refEarned); require( IERC20(rewardToken).transfer( stakingDetails[userAddress].referrer[stakeId], refEarned ) == true, "Transfer Failed" ); emit ReferralEarn( stakingDetails[userAddress].referrer[stakeId], _msgSender(), stakingDetails[userAddress].tokenAddress[stakeId], refEarned, block.timestamp ); } // Rewards Send sendToken( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], rewardToken, rewardsEarned ); } i = i + 1; } else { break; } } } /** * @notice Get rewards for one day * @param stakedAmount Stake amount of the user * @param stakedToken Staked token address of the user * @param rewardToken Reward token address * @return reward One dayh reward for the user */ function getOneDayReward( uint256 stakedAmount, address stakedToken, address rewardToken, uint256 totalStake ) public view returns (uint256 reward) { uint256 lockBenefit; if (tokenDetails[stakedToken].optionableStatus) { stakedAmount = stakedAmount.mul(optionableBenefit); lockBenefit = stakedAmount.mul(optionableBenefit.sub(1)); reward = ( stakedAmount.mul(tokenDailyDistribution[stakedToken][rewardToken]) ) .div(totalStake.add(lockBenefit)); } else { reward = ( stakedAmount.mul(tokenDailyDistribution[stakedToken][rewardToken]) ) .div(totalStake); } } /** * @notice Get rewards for one day * @param stakedToken Stake amount of the user * @param tokenAddress Reward token address * @param amount Amount to be transferred as reward */ function sendToken( address userAddress, address stakedToken, address tokenAddress, uint256 amount ) internal { // Checks if (tokenAddress != address(0)) { require( rewardCap[tokenAddress] >= amount, "SEND : Insufficient Reward Balance" ); // Transfer of rewards rewardCap[tokenAddress] = rewardCap[tokenAddress].sub(amount); require( IERC20(tokenAddress).transfer(userAddress, amount), "Transfer failed" ); // Emit state changes emit Claim( userAddress, stakedToken, tokenAddress, amount, block.timestamp ); } } /** * @notice Unstake and claim rewards * @param stakeId Stake ID of the user */ function unStake(address userAddress, uint256 stakeId) external whenNotPaused returns (bool) { require( _msgSender() == userAddress || _msgSender() == _owner, "UNSTAKE: Invalid User Entry" ); address stakedToken = stakingDetails[userAddress].tokenAddress[stakeId]; // lockableDays check require( tokenDetails[stakedToken].lockableDays <= block.timestamp, "UNSTAKE: Token Locked" ); // optional lock check if (tokenDetails[stakedToken].optionableStatus) require( stakingDetails[userAddress].startTime[stakeId].add(stakeDuration) <= block.timestamp, "UNSTAKE: Locked in optional lock" ); // Checks require( stakingDetails[userAddress].stakedAmount[stakeId] > 0 || stakingDetails[userAddress].isActive[stakeId] == true, "UNSTAKE : Already Claimed (or) Insufficient Staked" ); // State updation uint256 stakedAmount = stakingDetails[userAddress].stakedAmount[stakeId]; uint256 totalStaking1 = totalStaking[stakedToken]; totalStaking[stakedToken] = totalStaking[stakedToken].sub(stakedAmount); userTotalStaking[userAddress][stakedToken] = userTotalStaking[userAddress][ stakedToken ] .sub(stakedAmount); stakingDetails[userAddress].stakedAmount[stakeId] = 0; stakingDetails[userAddress].isActive[stakeId] = false; // Balance check require( IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).balanceOf( address(this) ) >= stakedAmount, "UNSTAKE : Insufficient Balance" ); // Transfer staked token back to user IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer( userAddress, stakedAmount ); claimRewards(userAddress, stakeId, stakedAmount, totalStaking1); // Emit state changes emit UnStake( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], stakedAmount, block.timestamp, stakeId ); return true; } function emergencyUnstake( uint256 stakeId, address userAddress, address[] memory rewardtokens, uint256[] memory amount ) external onlyOwner { // Checks require( stakingDetails[userAddress].stakedAmount[stakeId] > 0 && stakingDetails[userAddress].isActive[stakeId] == true, "EMERGENCY : Already Claimed (or) Insufficient Staked" ); // Balance check require( IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).balanceOf( address(this) ) >= stakingDetails[userAddress].stakedAmount[stakeId], "EMERGENCY : Insufficient Balance" ); uint256 stakeAmount = stakingDetails[userAddress].stakedAmount[stakeId]; stakingDetails[userAddress].isActive[stakeId] = false; stakingDetails[userAddress].stakedAmount[stakeId] = 0; totalStaking[ stakingDetails[userAddress].tokenAddress[stakeId] ] = totalStaking[stakingDetails[userAddress].tokenAddress[stakeId]].sub( stakeAmount ); IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer( userAddress, stakeAmount ); for (uint256 i; i < rewardtokens.length; i++) { uint256 rewardsEarned = amount[i]; if (stakingDetails[userAddress].referrer[stakeId] != address(0)) { uint256 refEarned = (rewardsEarned.mul(refPercentage)).div(100 ether); rewardsEarned = rewardsEarned.sub(refEarned); require( IERC20(rewardtokens[i]).transfer( stakingDetails[userAddress].referrer[stakeId], refEarned ), "EMERGENCY : Transfer Failed" ); emit ReferralEarn( stakingDetails[userAddress].referrer[stakeId], userAddress, rewardtokens[i], refEarned, block.timestamp ); } sendToken( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], rewardtokens[i], rewardsEarned ); } // Emit state changes emit UnStake( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], stakeAmount, block.timestamp, stakeId ); } /** * @notice View staking details * @param _user User address */ function viewStakingDetails(address _user) public view returns ( address[] memory, address[] memory, bool[] memory, uint256[] memory, uint256[] memory, uint256[] memory ) { return ( stakingDetails[_user].referrer, stakingDetails[_user].tokenAddress, stakingDetails[_user].isActive, stakingDetails[_user].stakeId, stakingDetails[_user].stakedAmount, stakingDetails[_user].startTime ); } /** * Override this function. * This version is to keep track of BaseRelayRecipient you are using * in your contract. */ function versionRecipient() external pure override returns (string memory) { return "1"; } function updateTrustForwarder(address _newTrustForwarder) external onlyOwner { trustedForwarder = _newTrustForwarder; } function pause() external onlyOwner returns (bool) { _pause(); return true; } function unpause() external onlyOwner returns (bool) { _unpause(); return true; } }
* @notice Unstake and claim rewards @param stakeId Stake ID of the user/ lockableDays check optional lock check Checks State updation Balance check Transfer staked token back to user Emit state changes
function unStake(address userAddress, uint256 stakeId) external whenNotPaused returns (bool) { require( _msgSender() == userAddress || _msgSender() == _owner, "UNSTAKE: Invalid User Entry" ); address stakedToken = stakingDetails[userAddress].tokenAddress[stakeId]; require( tokenDetails[stakedToken].lockableDays <= block.timestamp, "UNSTAKE: Token Locked" ); if (tokenDetails[stakedToken].optionableStatus) require( stakingDetails[userAddress].startTime[stakeId].add(stakeDuration) <= block.timestamp, "UNSTAKE: Locked in optional lock" ); require( stakingDetails[userAddress].stakedAmount[stakeId] > 0 || stakingDetails[userAddress].isActive[stakeId] == true, "UNSTAKE : Already Claimed (or) Insufficient Staked" ); uint256 stakedAmount = stakingDetails[userAddress].stakedAmount[stakeId]; uint256 totalStaking1 = totalStaking[stakedToken]; totalStaking[stakedToken] = totalStaking[stakedToken].sub(stakedAmount); userTotalStaking[userAddress][stakedToken] = userTotalStaking[userAddress][ stakedToken ] .sub(stakedAmount); stakingDetails[userAddress].stakedAmount[stakeId] = 0; stakingDetails[userAddress].isActive[stakeId] = false; require( IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).balanceOf( address(this) ) >= stakedAmount, "UNSTAKE : Insufficient Balance" ); IERC20(stakingDetails[userAddress].tokenAddress[stakeId]).transfer( userAddress, stakedAmount ); claimRewards(userAddress, stakeId, stakedAmount, totalStaking1); emit UnStake( userAddress, stakingDetails[userAddress].tokenAddress[stakeId], stakedAmount, block.timestamp, stakeId ); return true; }
6,521,959
[ 1, 984, 334, 911, 471, 7516, 283, 6397, 225, 384, 911, 548, 934, 911, 1599, 434, 326, 729, 19, 2176, 429, 9384, 866, 3129, 2176, 866, 13074, 3287, 2166, 367, 30918, 866, 12279, 384, 9477, 1147, 1473, 358, 729, 16008, 919, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 640, 510, 911, 12, 2867, 729, 1887, 16, 2254, 5034, 384, 911, 548, 13, 203, 565, 3903, 203, 565, 1347, 1248, 28590, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 2583, 12, 203, 1377, 389, 3576, 12021, 1435, 422, 729, 1887, 747, 389, 3576, 12021, 1435, 422, 389, 8443, 16, 203, 1377, 315, 2124, 882, 37, 6859, 30, 1962, 2177, 3841, 6, 203, 565, 11272, 203, 203, 565, 1758, 384, 9477, 1345, 273, 384, 6159, 3790, 63, 1355, 1887, 8009, 2316, 1887, 63, 334, 911, 548, 15533, 203, 203, 565, 2583, 12, 203, 1377, 1147, 3790, 63, 334, 9477, 1345, 8009, 739, 429, 9384, 1648, 1203, 18, 5508, 16, 203, 1377, 315, 2124, 882, 37, 6859, 30, 3155, 3488, 329, 6, 203, 565, 11272, 203, 203, 565, 309, 261, 2316, 3790, 63, 334, 9477, 1345, 8009, 3482, 429, 1482, 13, 203, 1377, 2583, 12, 203, 3639, 384, 6159, 3790, 63, 1355, 1887, 8009, 1937, 950, 63, 334, 911, 548, 8009, 1289, 12, 334, 911, 5326, 13, 1648, 203, 1850, 1203, 18, 5508, 16, 203, 3639, 315, 2124, 882, 37, 6859, 30, 3488, 329, 316, 3129, 2176, 6, 203, 1377, 11272, 203, 203, 565, 2583, 12, 203, 1377, 384, 6159, 3790, 63, 1355, 1887, 8009, 334, 9477, 6275, 63, 334, 911, 548, 65, 405, 374, 747, 203, 3639, 384, 6159, 3790, 63, 1355, 1887, 8009, 291, 3896, 63, 334, 911, 548, 65, 422, 638, 16, 203, 1377, 315, 2124, 882, 37, 6859, 294, 17009, 18381, 329, 261, 280, 13, 22085, 2 ]
./full_match/4/0xb1086EE7F3cbc3f45065cCc341854A71a94D9062/sources/contracts/ERC721.sol
@notice Count all NFTs assigned to an owner @dev NFTs assigned to the zero address are considered invalid, and this function throws for queries about the zero address. @param _owner An address for whom to query the balance @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) public view override returns (uint256) { require(_owner != address(0), "No NFT assigned to the zero address"); return _balances[_owner]; }
13,354,319
[ 1, 1380, 777, 423, 4464, 87, 6958, 358, 392, 3410, 225, 423, 4464, 87, 6958, 358, 326, 3634, 1758, 854, 7399, 2057, 16, 471, 333, 225, 445, 1216, 364, 6218, 2973, 326, 3634, 1758, 18, 225, 389, 8443, 1922, 1758, 364, 600, 362, 358, 843, 326, 11013, 327, 1021, 1300, 434, 423, 4464, 87, 16199, 635, 1375, 67, 8443, 9191, 10016, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 3631, 315, 2279, 423, 4464, 6958, 358, 326, 3634, 1758, 8863, 203, 3639, 327, 389, 70, 26488, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 27699, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; contract SafeMath { function safeMul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract QuantumXICO is ERC20, SafeMath { mapping(address => uint256) balances; uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ 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 approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } uint256 public endTime; modifier during_offering_time(){ if (now >= endTime) { throw; }else { _; } } function () payable during_offering_time { createTokens(msg.sender); } function createTokens(address recipient) payable { if (msg.value == 0) { throw; } uint tokens = safeDiv(safeMul(msg.value, price), 1 ether); totalSupply = safeAdd(totalSupply, tokens); balances[recipient] = safeAdd(balances[recipient], tokens); if (!owner.send(msg.value)) { throw; } } string public name = "QuantumXCoin"; string public symbol = "QTMX"; uint public decimals = 0; uint256 public INITIAL_SUPPLY = 1000000; uint256 public price; address public owner; function QuantumXICO() { totalSupply = INITIAL_SUPPLY; // Give all of the initial tokens to the contract deployer. balances[msg.sender] = INITIAL_SUPPLY; endTime = now + 1 weeks; owner = msg.sender; price = 100; } }
Give all of the initial tokens to the contract deployer.
function QuantumXICO() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; endTime = now + 1 weeks; owner = msg.sender; price = 100; }
924,899
[ 1, 43, 688, 777, 434, 326, 2172, 2430, 358, 326, 6835, 7286, 264, 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 ]
[ 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, 4783, 970, 379, 60, 2871, 51, 1435, 288, 203, 202, 202, 4963, 3088, 1283, 273, 28226, 67, 13272, 23893, 31, 203, 202, 202, 70, 26488, 63, 3576, 18, 15330, 65, 273, 28226, 67, 13272, 23893, 31, 203, 202, 202, 409, 950, 273, 2037, 397, 404, 17314, 31, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 202, 8694, 273, 2130, 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 ]
// SPDX-License-Identifier: (c) Armor.Fi DAO, 2021 pragma solidity ^0.6.12; interface IArmorMaster { function registerModule(bytes32 _key, address _module) external; function getModule(bytes32 _key) external view returns(address); function keep() external; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * @dev Completely default OpenZeppelin. */ contract Ownable { address private _owner; address private _pendingOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initializeOwnable() internal { require(_owner == address(0), "already initialized"); _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "msg.sender is not owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _pendingOwner = newOwner; } function receiveOwnership() public { require(msg.sender == _pendingOwner, "only pending owner can call this function"); _transferOwnership(_pendingOwner); _pendingOwner = address(0); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private __gap; } library Bytes32 { function toString(bytes32 x) internal pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } } /** * @dev Each arCore contract is a module to enable simple communication and interoperability. ArmorMaster.sol is master. **/ contract ArmorModule { IArmorMaster internal _master; using Bytes32 for bytes32; modifier onlyOwner() { require(msg.sender == Ownable(address(_master)).owner(), "only owner can call this function"); _; } modifier doKeep() { _master.keep(); _; } modifier onlyModule(bytes32 _module) { string memory message = string(abi.encodePacked("only module ", _module.toString()," can call this function")); require(msg.sender == getModule(_module), message); _; } /** * @dev Used when multiple can call. **/ modifier onlyModules(bytes32 _moduleOne, bytes32 _moduleTwo) { string memory message = string(abi.encodePacked("only module ", _moduleOne.toString()," or ", _moduleTwo.toString()," can call this function")); require(msg.sender == getModule(_moduleOne) || msg.sender == getModule(_moduleTwo), message); _; } function initializeModule(address _armorMaster) internal { require(address(_master) == address(0), "already initialized"); require(_armorMaster != address(0), "master cannot be zero address"); _master = IArmorMaster(_armorMaster); } function changeMaster(address _newMaster) external onlyOwner { _master = IArmorMaster(_newMaster); } function getModule(bytes32 _key) internal view returns(address) { return _master.getModule(_key); } } /** * @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); } interface IARNXMVault { function unwrapWnxm() external; function buyNxmWithEther(uint256 _minAmount) external payable; } interface IClaimManager { function initialize(address _armorMaster) external; function transferNft(address _to, uint256 _nftId) external; function exchangeWithdrawal(uint256 _amount) external; } /** * @dev Quick interface for the Nexus Mutual contract to work with the Armor Contracts. **/ // to get nexus mutual contract address interface INXMMaster { function tokenAddress() external view returns(address); function owner() external view returns(address); function pauseTime() external view returns(uint); function masterInitialized() external view returns(bool); function isPause() external view returns(bool check); function isMember(address _add) external view returns(bool); function getLatestAddress(bytes2 _contractName) external view returns(address payable contractAddress); } interface INXMPool { function buyNXM(uint minTokensOut) external payable; } interface IBFactory { function isBPool(address _pool) external view returns(bool); } interface IBPool { function swapExactAmountIn(address tokenin, uint256 inamount, address out, uint256 minreturn, uint256 maxprice) external returns(uint tokenAmountOut, uint spotPriceAfter); } interface IUniswapV2Router02 { function swapExactETHForTokens(uint256 minReturn, address[] calldata path, address to, uint256 deadline) external payable returns(uint256[] memory); } interface IWETH { function deposit() external payable; function withdraw(uint256 amount) external; } /** * ExchangeManager contract enables us to slowly exchange excess claim funds for wNXM then transfer to the arNXM vault. **/ contract ExchangeManager is ArmorModule { address public exchanger; IARNXMVault public constant ARNXM_VAULT = IARNXMVault(0x1337DEF1FC06783D4b03CB8C1Bf3EBf7D0593FC4); IERC20 public constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 public constant WNXM = IERC20(0x0d438F3b5175Bebc262bF23753C1E53d03432bDE); INXMMaster public constant NXM_MASTER = INXMMaster(0x01BFd82675DBCc7762C84019cA518e701C0cD07e); IBFactory public constant BALANCER_FACTORY = IBFactory(0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd); IUniswapV2Router02 public constant UNI_ROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); IUniswapV2Router02 public constant SUSHI_ROUTER = IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Address allowed to exchange tokens. modifier onlyExchanger { require(msg.sender == exchanger, "Sender is not approved to exchange."); _; } // ClaimManager will be sending Ether to this contract. receive() external payable { } /** * @dev Initialize master for the contract. Owner must also add module for ExchangeManager to master upon deployment. * @param _armorMaster Address of the ArmorMaster contract. **/ function initialize(address _armorMaster, address _exchanger) external { initializeModule(_armorMaster); exchanger = _exchanger; } /** * @dev Main function to withdraw Ether from ClaimManager, exchange, then transfer to arNXM Vault. * @param _amount Amount of Ether (in Wei) to withdraw from ClaimManager. * @param _minReturn Minimum amount of wNXM we will accept in return for the Ether exchanged. **/ function buyWNxmUni(uint256 _amount, uint256 _minReturn, address[] memory _path) external onlyExchanger { _requestFunds(_amount); _exchangeAndSendToVault(address(UNI_ROUTER), _minReturn, _path); } /** * @dev Main function to withdraw Ether from ClaimManager, exchange, then transfer to arNXM Vault. * @param _amount Amount of Ether (in Wei) to withdraw from ClaimManager. * @param _minReturn Minimum amount of wNXM we will accept in return for the Ether exchanged. **/ function buyWNxmSushi(uint256 _amount, uint256 _minReturn, address[] memory _path) external onlyExchanger { _requestFunds(_amount); _exchangeAndSendToVault(address(SUSHI_ROUTER), _minReturn, _path); } function buyWNxmBalancer(uint256 _amount, address _bpool, uint256 _minReturn, uint256 _maxPrice) external onlyExchanger { require(BALANCER_FACTORY.isBPool(_bpool), "NOT_BPOOL"); _requestFunds(_amount); uint256 balance = address(this).balance; IWETH(address(WETH)).deposit{value:balance}(); WETH.approve(_bpool, balance); IBPool(_bpool).swapExactAmountIn(address(WETH), balance, address(WNXM), _minReturn, _maxPrice); _transferWNXM(); ARNXM_VAULT.unwrapWnxm(); } /** * @dev Main function to withdraw Ether from ClaimManager, exchange, then transfer to arNXM Vault. * @param _ethAmount Amount of Ether (in Wei) to withdraw from ClaimManager. * @param _minNxm Minimum amount of NXM we will accept in return for the Ether exchanged. **/ function buyNxm(uint256 _ethAmount, uint256 _minNxm) external onlyExchanger { _requestFunds(_ethAmount); ARNXM_VAULT.buyNxmWithEther{value:_ethAmount}(_minNxm); } /** * @dev Call ClaimManager to request Ether from the contract. * @param _amount Ether (in Wei) to withdraw from ClaimManager. **/ function _requestFunds(uint256 _amount) internal { IClaimManager( getModule("CLAIM") ).exchangeWithdrawal(_amount); } /** * @dev Exchange all Ether for wNXM on uniswap-like exchanges * @param _router router address of uniswap-like protocols(uni/sushi) * @param _minReturn Minimum amount of wNXM we wish to receive from the exchange. **/ function _exchangeAndSendToVault(address _router, uint256 _minReturn, address[] memory _path) internal { uint256 ethBalance = address(this).balance; IUniswapV2Router02(_router).swapExactETHForTokens{value:ethBalance}(_minReturn, _path, address(ARNXM_VAULT), uint256(~0) ); ARNXM_VAULT.unwrapWnxm(); } /** * @dev Transfer all wNXM directly to arNXM. This will not mint more arNXM so it will add value to arNXM. **/ function _transferWNXM() internal { uint256 wNxmBalance = WNXM.balanceOf( address(this) ); WNXM.transfer(address(ARNXM_VAULT), wNxmBalance); } /** * @dev Transfer all NXM directly to arNXM. This will not mint more arNXM so it will add value to arNXM. **/ function _transferNXM() internal { IERC20 NXM = IERC20(NXM_MASTER.tokenAddress()); uint256 nxmBalance = NXM.balanceOf( address(this) ); NXM.transfer(address(ARNXM_VAULT), nxmBalance); } /** * @dev Owner may change the address allowed to exchange tokens. * @param _newExchanger New address to make exchanger. **/ function changeExchanger(address _newExchanger) external onlyOwner { exchanger = _newExchanger; } }
* @dev Transfer all wNXM directly to arNXM. This will not mint more arNXM so it will add value to arNXM./
function _transferWNXM() internal { uint256 wNxmBalance = WNXM.balanceOf( address(this) ); WNXM.transfer(address(ARNXM_VAULT), wNxmBalance); }
175,183
[ 1, 5912, 777, 341, 17106, 49, 5122, 358, 419, 17106, 49, 18, 1220, 903, 486, 312, 474, 1898, 419, 17106, 49, 1427, 518, 903, 527, 460, 358, 419, 17106, 49, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 5665, 60, 49, 1435, 203, 1377, 2713, 203, 565, 288, 203, 3639, 2254, 5034, 341, 50, 92, 81, 13937, 273, 678, 17106, 49, 18, 12296, 951, 12, 1758, 12, 2211, 13, 11272, 203, 3639, 678, 17106, 49, 18, 13866, 12, 2867, 12, 4391, 60, 49, 67, 27722, 2274, 3631, 341, 50, 92, 81, 13937, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; /** * @title ConstitutionalDNA * @author ola * --- Collaborators --- * @author zlatinov * @author panos * @author yemi * @author archil * @author anthony */ contract ConstitutionalDNA { struct Person{ address addr; bytes name; bytes role; uint rank; } bool onceFlag = false; bool isRatified = false; address home = 0x0; //consensusX housing address[]foundingTeamAddresses; // iterable list of addresses mapping (address => Person) public foundingTeam; //foundingteam mapping(address => bool) mutify; uint ratifyCount; /** * @notice Deploying Constitution contract. Setting `msg.sender.address()` as Founder * @dev Deploy and instantiate the Constitution contract */ function ConstitutionalDNA(){ foundingTeam[msg.sender].addr = msg.sender; foundingTeam[msg.sender].role = "Founder"; foundingTeam[msg.sender].rank = 1; foundingTeamAddresses.push(msg.sender); } struct Articles { bytes article; uint articleNum; uint itemNums; bytes[] items; bool amendable; bool set; } uint articleNumbers = 0; Articles[] public constitutionalArticles; event ArticleAddedEvent(uint indexed articleId, bytes articleHeading, bool amendable); event ArticleItemAddedEvent(uint indexed articleId, uint indexed itemId, bytes itemText); event ArticleAmendedEvent(uint indexed articleId, uint indexed itemId, bytes newItemText); event ProfileUpdateEvent(address profileAddress, bytes profileName); event FoundingTeamSetEvent(address[] foundingTeam, uint[] ranks); event HomeSetEvent(address home); /** * @notice Adding new article: `_aticle` * @dev Add new article to the constituitionalDNA. And fire event if successful * @param _article Article name or title to be stored * @param _amendable True if Article is amendable */ function addArticle(bytes _article, bool _amendable) external founderCheck ratified homeIsSet { constitutionalArticles.length = articleNumbers+1; constitutionalArticles[articleNumbers].article = _article; constitutionalArticles[articleNumbers].articleNum = articleNumbers; constitutionalArticles[articleNumbers].amendable = _amendable; constitutionalArticles[articleNumbers].set = true; ArticleAddedEvent(articleNumbers, _article, _amendable); articleNumbers++; } /** * @notice Adding new Item to article: `String(constitutionalArticles[_articleNum].article)` * @dev Add a new Item to an article denoted by articleNum which is the article's index in the constitutionalArticles array. Fires the AddedItem event if successful * @param _articleNum The index of the article in the constitutionalArticles array which the item is added to * @param _itemText The Content/Data of the item */ function addArticleItem(uint _articleNum, bytes _itemText) external founderCheck articleSet(_articleNum) ratified homeIsSet { uint itemId = constitutionalArticles[_articleNum].itemNums; constitutionalArticles[_articleNum].items.length = itemId+1; constitutionalArticles[_articleNum].items[itemId] = _itemText; constitutionalArticles[_articleNum].itemNums++; ArticleItemAddedEvent(_articleNum, itemId, _itemText); } /** * @notice Updating item with index: `_item` of article: `String(constitutionalArticles[_articleNum].article)` * @dev Update Content of Item by idicating the item index in the article.items array and the article index in the constitutionalArticles array. Fires the Amended event if successful * @param _articleNum The index of the article in the constitutionalArticles array * @param _item The index of the item in the article.item array * @param _textChange The data to be updated into the item Position in the article.item array */ function amendArticleItem(uint _articleNum, uint _item, bytes _textChange) articleSet(_articleNum) updaterCheck amendable(_articleNum) { constitutionalArticles[_articleNum].items[_item] = _textChange; ArticleAmendedEvent(_articleNum, _item, _textChange); } /** * @notice Retreiving article item details from item: `_item` of article: `String(constitutionalArticles[_articleNum].article)` * @dev Retreive Item data from Article array * @param _articleNum The index of the article in the constitutionalArticles array * @param _item The index of the item in the article.item array * @return article Name/Title of the article under which the item is indexed * @return articleNum The index of the article in the constitutionalArticles array * @return amendable True if the item is amendable or can be updated * @return items[_item] The data of the Item being retreived */ function getArticleItem(uint _articleNum, uint _item) public constant returns (bytes article, uint articleNum, bool amendible, bytes itemText) { return ( constitutionalArticles[_articleNum].article, constitutionalArticles[_articleNum].articleNum, constitutionalArticles[_articleNum].amendable, constitutionalArticles[_articleNum].items[_item] ); } /** * @notice `msg.sender.address()` confirming the contract and articles * @dev Founding Team ratify/approve the contract and articles. Once completed by all founding team members, Incrementing ratifyCount at each turn. Deactivates adding articles or items * @return True if completely ratified else false */ function initializedRatify() external foundingTeamCheck foundationNotSet mutifyAlreadySet returns (bool success) { if (ratifyCount == foundingTeamAddresses.length) { isRatified = true; return true; } else { mutify[msg.sender] == true; ratifyCount++; return false; } } /** * @notice Adding founding team members to founding Team list * @dev Add array of new Founding team member to the foundingTeam list * @param _founderRanks Array of rank/index of the founding Team members * @param _founderAddrs Array of founding Team members matching the indexes in the _founderRanks array */ function setFoundingTeam(uint[] _founderRanks, address[] _founderAddrs) external founderCheck foundingTeamListHasFounder(_founderRanks,_founderAddrs) foundingTeamMatchRank(_founderRanks,_founderAddrs) { for(uint i = 1; i <_founderRanks.length; i++) { foundingTeamAddresses.push(_founderAddrs[i]); foundingTeam[_founderAddrs[i]].addr = _founderAddrs[i]; foundingTeam[_founderAddrs[i]].rank = _founderRanks[i]; } FoundingTeamSetEvent(_founderAddrs, _founderRanks); } /** * @notice Updating Profile information of `msg.sender.address()` * @dev Update the profile information of a founding Team member using mssg.sender as the index. Enable any founder to update name and address. Fire FounderUpdate event if successful * @param _addr Address of the founding Team member * @param _profileName Profile name to be updated to the founding Team Array */ function updateProfile(address _addr, bytes _profileName) foundingTeamCheck { foundingTeam[_addr].addr = _addr; foundingTeam[msg.sender].name = _profileName; ProfileUpdateEvent(_addr, _profileName); } /** * @notice Setting consensusX address to `_consensusX.address()` * @dev set consensusX in which the Constitution is housed * @param _consensusX Address of the consensusX on the blockchain */ function setHome (address _consensusX) founderCheck once { home = _consensusX; HomeSetEvent(home); } modifier founderCheck() { var (tempAddr, tempRank) = (foundingTeam[msg.sender].addr, foundingTeam[msg.sender].rank); if(tempAddr != msg.sender || tempRank != 1 ) throw; _; } modifier foundationNotSet(){ if(foundingTeam[msg.sender].rank != 1 && mutify[foundingTeamAddresses[0]] == false) throw; _; } modifier mutifyAlreadySet(){ if (mutify[msg.sender] == true) throw; _; } modifier foundingTeamCheck(){ if(msg.sender != foundingTeam[msg.sender].addr) throw; _; } modifier articleSet(uint _articleNumber){ if(constitutionalArticles[_articleNumber].set != true) throw; _; } modifier updaterCheck(){ if (msg.sender != home) throw; _; } modifier once(){ if (onceFlag == true) throw; onceFlag = true; _; } modifier amendable(uint _articleNum){ if (constitutionalArticles[_articleNum].amendable == false) throw; _; } modifier homeIsSet(){ if (home == 0x0) throw; _; } modifier ratified(){ if (foundingTeam[msg.sender].rank == 1 && isRatified == true) throw; _; } modifier foundingTeamMatchRank(uint[] _founderRanks,address[] _founderAddrs){ if(_founderRanks.length != _founderAddrs.length) throw; _; } modifier foundingTeamListHasFounder(uint[] _founderRanks,address[] _founderAddrs){ if(_founderAddrs[0] != foundingTeamAddresses[0] || _founderRanks[0] != 1) throw; _; } /* * Safeguard function. * This function gets executed if a transaction with invalid data is sent to * the contract or just ether without data. */ function (){ throw; } }
* @notice Deploying Constitution contract. Setting `msg.sender.address()` as Founder @dev Deploy and instantiate the Constitution contract/
function ConstitutionalDNA(){ foundingTeam[msg.sender].addr = msg.sender; foundingTeam[msg.sender].role = "Founder"; foundingTeam[msg.sender].rank = 1; foundingTeamAddresses.push(msg.sender); }
14,035,396
[ 1, 10015, 310, 735, 14278, 6835, 18, 13274, 1375, 3576, 18, 15330, 18, 2867, 20338, 487, 478, 465, 765, 225, 7406, 471, 10275, 326, 735, 14278, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1377, 445, 735, 14278, 287, 8609, 37, 1435, 95, 203, 1850, 1392, 310, 8689, 63, 3576, 18, 15330, 8009, 4793, 273, 1234, 18, 15330, 31, 203, 1850, 1392, 310, 8689, 63, 3576, 18, 15330, 8009, 4615, 273, 315, 42, 465, 765, 14432, 203, 1850, 1392, 310, 8689, 63, 3576, 18, 15330, 8009, 11500, 273, 404, 31, 203, 1850, 1392, 310, 8689, 7148, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 1377, 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 ]
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; import {IFollowNFT} from '../interfaces/IFollowNFT.sol'; import {IFollowModule} from '../interfaces/IFollowModule.sol'; import {ILensHub} from '../interfaces/ILensHub.sol'; import {Errors} from '../libraries/Errors.sol'; import {Events} from '../libraries/Events.sol'; import {DataTypes} from '../libraries/DataTypes.sol'; import {LensNFTBase} from './base/LensNFTBase.sol'; import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; /** * @title FollowNFT * @author Lens Protocol * * @notice This contract is the NFT that is minted upon following a given profile. It is cloned upon first follow for a * given profile, and includes built-in governance power and delegation mechanisms. * * NOTE: This contract assumes total NFT supply for this follow NFT will never exceed 2^128 - 1 */ contract FollowNFT is LensNFTBase, IFollowNFT { struct Snapshot { uint128 blockNumber; uint128 value; } address public immutable HUB; bytes32 internal constant DELEGATE_BY_SIG_TYPEHASH = 0xb8f190a57772800093f4e2b186099eb4f1df0ed7f5e2791e89a4a07678e0aeff; // keccak256( // 'DelegateBySig(address delegator,address delegatee,uint256 nonce,uint256 deadline)' // ); mapping(address => mapping(uint256 => Snapshot)) internal _snapshots; mapping(address => address) internal _delegates; mapping(address => uint256) internal _snapshotCount; mapping(uint256 => Snapshot) internal _delSupplySnapshots; uint256 internal _delSupplySnapshotCount; uint256 internal _profileId; uint256 internal _tokenIdCounter; bool private _initialized; // We create the FollowNFT with the pre-computed HUB address before deploying the hub. constructor(address hub) { HUB = hub; } /// @inheritdoc IFollowNFT function initialize( uint256 profileId, string calldata name, string calldata symbol ) external override { if (_initialized) revert Errors.Initialized(); _initialized = true; _profileId = profileId; super._initialize(name, symbol); emit Events.FollowNFTInitialized(profileId, block.timestamp); } /// @inheritdoc IFollowNFT function mint(address to) external override { if (msg.sender != HUB) revert Errors.NotHub(); uint256 tokenId = ++_tokenIdCounter; _mint(to, tokenId); } /// @inheritdoc IFollowNFT function delegate(address delegatee) external override { _delegate(msg.sender, delegatee); } /// @inheritdoc IFollowNFT function delegateBySig( address delegator, address delegatee, DataTypes.EIP712Signature calldata sig ) external override { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( DELEGATE_BY_SIG_TYPEHASH, delegator, delegatee, sigNonces[delegator]++, sig.deadline ) ) ), delegator, sig ); _delegate(delegator, delegatee); } /// @inheritdoc IFollowNFT function getPowerByBlockNumber(address user, uint256 blockNumber) external view override returns (uint256) { if (blockNumber > block.number) revert Errors.BlockNumberInvalid(); uint256 snapshotCount = _snapshotCount[user]; if (snapshotCount == 0) { return 0; // Returning zero since this means the user never delegated and has no power } uint256 lower = 0; uint256 upper = snapshotCount - 1; // First check most recent balance if (_snapshots[user][upper].blockNumber <= blockNumber) { return _snapshots[user][upper].value; } // Next check implicit zero balance if (_snapshots[user][lower].blockNumber > blockNumber) { return 0; } while (upper > lower) { uint256 center = upper - (upper - lower) / 2; Snapshot memory snapshot = _snapshots[user][center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return _snapshots[user][lower].value; } /// @inheritdoc IFollowNFT function getDelegatedSupplyByBlockNumber(uint256 blockNumber) external view override returns (uint256) { if (blockNumber > block.number) revert Errors.BlockNumberInvalid(); uint256 snapshotCount = _delSupplySnapshotCount; if (snapshotCount == 0) { return 0; // Returning zero since this means a delegation has never occurred } uint256 lower = 0; uint256 upper = snapshotCount - 1; // First check most recent delegated supply if (_delSupplySnapshots[upper].blockNumber <= blockNumber) { return _delSupplySnapshots[upper].value; } // Next check implicit zero balance if (_delSupplySnapshots[lower].blockNumber > blockNumber) { return 0; } while (upper > lower) { uint256 center = upper - (upper - lower) / 2; Snapshot memory snapshot = _delSupplySnapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return _delSupplySnapshots[lower].value; } /** * @dev This returns the follow NFT URI fetched from the hub. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { if (!_exists(tokenId)) revert Errors.TokenDoesNotExist(); return ILensHub(HUB).getFollowNFTURI(_profileId); } /** * @dev Upon transfers, we move the appropriate delegations, and emit the transfer event in the hub. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { address fromDelegatee = _delegates[from]; address toDelegatee = _delegates[to]; address followModule = ILensHub(HUB).getFollowModule(_profileId); _moveDelegate(fromDelegatee, toDelegatee, 1); super._beforeTokenTransfer(from, to, tokenId); ILensHub(HUB).emitFollowNFTTransferEvent(_profileId, tokenId, from, to); if (followModule != address(0)) { IFollowModule(followModule).followModuleTransferHook(_profileId, from, to, tokenId); } } function _delegate(address delegator, address delegatee) internal { uint256 delegatorBalance = balanceOf(delegator); address previousDelegate = _delegates[delegator]; _delegates[delegator] = delegatee; _moveDelegate(previousDelegate, delegatee, delegatorBalance); } function _moveDelegate( address from, address to, uint256 amount ) internal { unchecked { if (from != address(0)) { uint256 fromSnapshotCount = _snapshotCount[from]; // Underflow is impossible since, if from != address(0), then a delegation must have occurred (at least 1 snapshot) uint256 previous = _snapshots[from][fromSnapshotCount - 1].value; uint128 newValue = uint128(previous - amount); _writeSnapshot(from, newValue, fromSnapshotCount); emit Events.FollowNFTDelegatedPowerChanged(from, newValue, block.timestamp); } if (to != address(0)) { // if from == address(0) then this is an initial delegation (add amount to supply) if (from == address(0)) { // It is expected behavior that the `previousDelSupply` underflows upon the first delegation, // returning the expected value of zero uint256 delSupplySnapshotCount = _delSupplySnapshotCount; uint128 previousDelSupply = _delSupplySnapshots[delSupplySnapshotCount - 1] .value; uint128 newDelSupply = uint128(previousDelSupply + amount); _writeSupplySnapshot(newDelSupply, delSupplySnapshotCount); } // It is expected behavior that `previous` underflows upon the first delegation to an address, // returning the expected value of zero uint256 toSnapshotCount = _snapshotCount[to]; uint128 previous = _snapshots[to][toSnapshotCount - 1].value; uint128 newValue = uint128(previous + amount); _writeSnapshot(to, newValue, toSnapshotCount); emit Events.FollowNFTDelegatedPowerChanged(to, newValue, block.timestamp); } else { // If from != address(0) then this is removing a delegation, otherwise we're dealing with a // non-delegated burn of tokens and don't need to take any action if (from != address(0)) { // Upon removing delegation (from != address(0) && to == address(0)), supply calculations cannot // underflow because if from != address(0), then a delegation must have previously occurred, so // the snapshot count must be >= 1 and the previous delegated supply must be >= amount uint256 delSupplySnapshotCount = _delSupplySnapshotCount; uint128 previousDelSupply = _delSupplySnapshots[delSupplySnapshotCount - 1] .value; uint128 newDelSupply = uint128(previousDelSupply - amount); _writeSupplySnapshot(newDelSupply, delSupplySnapshotCount); } } } } function _writeSnapshot( address owner, uint128 newValue, uint256 ownerSnapshotCount ) internal { unchecked { uint128 currentBlock = uint128(block.number); mapping(uint256 => Snapshot) storage ownerSnapshots = _snapshots[owner]; // Doing multiple operations in the same block if ( ownerSnapshotCount != 0 && ownerSnapshots[ownerSnapshotCount - 1].blockNumber == currentBlock ) { ownerSnapshots[ownerSnapshotCount - 1].value = newValue; } else { ownerSnapshots[ownerSnapshotCount] = Snapshot(currentBlock, newValue); _snapshotCount[owner] = ownerSnapshotCount + 1; } } } function _writeSupplySnapshot(uint128 newValue, uint256 supplySnapshotCount) internal { unchecked { uint128 currentBlock = uint128(block.number); // Doing multiple operations in the same block if ( supplySnapshotCount != 0 && _delSupplySnapshots[supplySnapshotCount - 1].blockNumber == currentBlock ) { _delSupplySnapshots[supplySnapshotCount - 1].value = newValue; } else { _delSupplySnapshots[supplySnapshotCount] = Snapshot(currentBlock, newValue); _delSupplySnapshotCount = supplySnapshotCount + 1; } } } }
@inheritdoc IFollowNFT First check most recent balance Next check implicit zero balance
function getPowerByBlockNumber(address user, uint256 blockNumber) external view override returns (uint256) { if (blockNumber > block.number) revert Errors.BlockNumberInvalid(); uint256 snapshotCount = _snapshotCount[user]; if (snapshotCount == 0) { } uint256 lower = 0; uint256 upper = snapshotCount - 1; if (_snapshots[user][upper].blockNumber <= blockNumber) { return _snapshots[user][upper].value; } if (_snapshots[user][lower].blockNumber > blockNumber) { return 0; } while (upper > lower) { uint256 center = upper - (upper - lower) / 2; Snapshot memory snapshot = _snapshots[user][center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; lower = center; upper = center - 1; } } return _snapshots[user][lower].value; }
6,345,857
[ 1, 36, 10093, 467, 8328, 50, 4464, 5783, 866, 4486, 8399, 11013, 4804, 866, 10592, 3634, 11013, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 2085, 858, 1768, 1854, 12, 2867, 729, 16, 2254, 5034, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 2629, 1854, 405, 1203, 18, 2696, 13, 15226, 9372, 18, 1768, 1854, 1941, 5621, 203, 203, 3639, 2254, 5034, 4439, 1380, 273, 389, 11171, 1380, 63, 1355, 15533, 203, 203, 3639, 309, 261, 11171, 1380, 422, 374, 13, 288, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2612, 273, 374, 31, 203, 3639, 2254, 5034, 3854, 273, 4439, 1380, 300, 404, 31, 203, 203, 3639, 309, 261, 67, 26918, 63, 1355, 6362, 5797, 8009, 2629, 1854, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 389, 26918, 63, 1355, 6362, 5797, 8009, 1132, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 26918, 63, 1355, 6362, 8167, 8009, 2629, 1854, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 2254, 5034, 4617, 273, 3854, 300, 261, 5797, 300, 2612, 13, 342, 576, 31, 203, 5411, 10030, 3778, 4439, 273, 389, 26918, 63, 1355, 6362, 5693, 15533, 203, 5411, 309, 261, 11171, 18, 2629, 1854, 422, 1203, 1854, 13, 288, 203, 7734, 327, 4439, 18, 1132, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 389, 26918, 63, 1355, 6362, 8167, 8009, 1132, 31, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 fromBlock; uint256 votes; } contract ProjectToken is IERC20, ReentrancyGuard { using SafeMath for uint256; /// @notice A record of each accounts delegate mapping(address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint256) public numCheckpoints; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); uint256 public override totalSupply; string public symbol; uint8 public decimals; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; constructor(string memory _symbol) public { symbol = _symbol; decimals = 18; } function getChainId() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } return chainId; } function balanceOf(address account) public view override returns (uint256 free) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address account_owner, address spender) public view virtual override returns (uint256) { return _allowances[account_owner][spender]; } function approve(address spender, uint256 amount) public virtual override nonReentrant returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual nonReentrant returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == block.number ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( block.number, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public nonReentrant { return _delegate(msg.sender, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "StakingToken: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint256 delegatorBalance = _balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { // if (from == address(0)) { // // When minting tokens // uint256 newSupply = totalSupply().add(amount); // require( // newSupply <= _softcap && newSupply <= _cap, // "ERC20Capped: cap exceeded" // ); // } } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual { _moveDelegates(from, to, amount); } function _approve( address account_owner, address spender, uint256 amount ) internal virtual { require( account_owner != address(0), "ERC20: approve from the zero address" ); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[account_owner][spender] = amount; emit Approval(account_owner, spender, 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); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); totalSupply = totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); _afterTokenTransfer(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); _afterTokenTransfer(account, address(0), amount); } }
* @notice Gets the current votes balance for `account` @param account The address to get votes balance @return The number of current votes for `account`/
function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; }
1,758,305
[ 1, 3002, 326, 783, 19588, 11013, 364, 1375, 4631, 68, 225, 2236, 1021, 1758, 358, 336, 19588, 11013, 327, 1021, 1300, 434, 783, 19588, 364, 1375, 4631, 68, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 5175, 29637, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 327, 203, 5411, 290, 1564, 4139, 405, 374, 692, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 294, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // The GNU General Public License v3 // &#169; Musqogees Tech 2018, Redenom ™ // -------------------- SAFE MATH ---------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // Basic ERC20 functions // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract manages Owner and Admin rights. // Owner is Admin by default and can set other Admin // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; address internal admin; // modifier for Owner functions modifier onlyOwner { require(msg.sender == owner); _; } // modifier for Admin functions modifier onlyAdmin { require(msg.sender == admin || msg.sender == owner); _; } event OwnershipTransferred(address indexed _from, address indexed _to); event AdminChanged(address indexed _from, address indexed _to); // Constructor function Owned() public { owner = msg.sender; admin = msg.sender; } function setAdmin(address newAdmin) public onlyOwner{ emit AdminChanged(admin, newAdmin); admin = newAdmin; } function showAdmin() public view onlyAdmin returns(address _admin){ _admin = admin; return _admin; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Redenom is ERC20Interface, Owned{ using SafeMath for uint; //ERC20 params string public name; // ERC20 string public symbol; // ERC20 uint private _totalSupply; // ERC20 uint public decimals = 8; // ERC20 //Redenomination uint public round = 1; uint public epoch = 1; bool public frozen = false; //dec - sum of every exponent uint[8] private dec = [0,0,0,0,0,0,0,0]; //mul - internal used array for splitting numbers according to round uint[9] private mul = [1,10,100,1000,10000,100000,1000000,10000000,100000000]; //weight - internal used array (weights of every digit) uint[9] private weight = [uint(0),0,0,0,0,5,10,30,55]; //current_toadd - After redenominate() it holds an amount to add on each digit. uint[9] private current_toadd = [uint(0),0,0,0,0,0,0,0,0]; //Funds uint public total_fund; // All funds for all epochs 1 000 000 NOM uint public epoch_fund; // All funds for current epoch 100 000 NOM uint public team_fund; // Team Fund 10% of all funds paid uint public redenom_dao_fund; // DAO Fund 30% of all funds paid struct Account { uint balance; uint lastRound; // Last round dividens paid uint lastVotedBallotId; // Last epoch user voted uint bitmask; // 2 - got 0.55... for phone verif. // 4 - got 1 for KYC // 1024 - banned // // [2] [4] 8 16 32 64 128 256 512 [1024] ... - free to use } mapping(address=>Account) accounts; mapping(address => mapping(address => uint)) allowed; //Redenom special events event Redenomination(uint indexed round); event Epoch(uint indexed epoch); event VotingOn(uint indexed _ballotId); event VotingOff(uint indexed winner); event Vote(address indexed voter, uint indexed propId, uint voterBalance, uint indexed curentBallotId); function Redenom() public { symbol = "NOMT"; name = "Redenom_test"; _totalSupply = 0; // total NOM&#39;s in the game total_fund = 1000000 * 10**decimals; // 1 000 000.00000000, 1Mt epoch_fund = 100000 * 10**decimals; // 100 000.00000000, 100 Kt total_fund = total_fund.sub(epoch_fund); // Taking 100 Kt from total to epoch_fund } // New epoch can be started if: // - Current round is 9 // - Curen epoch < 10 // - Voting is over function StartNewEpoch() public onlyAdmin returns(bool succ){ require(frozen == false); require(round == 9); require(epoch < 10); require(votingActive == false); dec = [0,0,0,0,0,0,0,0]; round = 1; epoch++; epoch_fund = 100000 * 10**decimals; // 100 000.00000000, 100 Kt total_fund = total_fund.sub(epoch_fund); // Taking 100 Kt from total to epoch fund emit Epoch(epoch); return true; } ///////////////////////////////////////////B A L L O T//////////////////////////////////////////// /* struct Account { uint balance; uint lastRound; // Last round dividens paid uint lastVotedBallotId; // Last epoch user voted uint[] parts; // Users parts in voted projects uint bitmask; */ //Is voting active? bool public votingActive = false; uint public curentBallotId = 0; uint public curentWinner; // Voter requirements: modifier onlyVoter { require(votingActive == true); require(bitmask_check(msg.sender, 4) == true); //passed KYC require(bitmask_check(msg.sender, 1024) == false); // banned == false require((accounts[msg.sender].lastVotedBallotId < curentBallotId)); _; } // This is a type for a single Project. struct Project { uint id; // Project id uint votesWeight; // total weight bool active; //active status. } Project[] public projects; struct Winner { uint id; uint projId; } Winner[] public winners; function addWinner(uint projId) internal { winners.push(Winner({ id: curentBallotId, projId: projId })); } function findWinner(uint _ballotId) public constant returns (uint winner){ for (uint p = 0; p < winners.length; p++) { if (winners[p].id == _ballotId) { return winners[p].projId; } } } // Add prop. with id: _id function addProject(uint _id) public onlyAdmin { projects.push(Project({ id: _id, votesWeight: 0, active: true })); } // Turns project ON and OFF function swapProject(uint _id) public onlyAdmin { for (uint p = 0; p < projects.length; p++){ if(projects[p].id == _id){ if(projects[p].active == true){ projects[p].active = false; }else{ projects[p].active = true; } } } } // Returns proj. weight function projectWeight(uint _id) public constant returns(uint PW){ for (uint p = 0; p < projects.length; p++){ if(projects[p].id == _id){ return projects[p].votesWeight; } } } // Returns proj. status function projectActive(uint _id) public constant returns(bool PA){ for (uint p = 0; p < projects.length; p++){ if(projects[p].id == _id){ return projects[p].active; } } } // Vote for proj. using id: _id function vote(uint _id) public onlyVoter returns(bool success){ require(frozen == false); for (uint p = 0; p < projects.length; p++){ if(projects[p].id == _id && projects[p].active == true){ projects[p].votesWeight += sqrt(accounts[msg.sender].balance); accounts[msg.sender].lastVotedBallotId = curentBallotId; } } emit Vote(msg.sender, _id, accounts[msg.sender].balance, curentBallotId); return true; } // Shows currently winning proj function winningProject() public constant returns (uint _winningProject){ uint winningVoteWeight = 0; for (uint p = 0; p < projects.length; p++) { if (projects[p].votesWeight > winningVoteWeight && projects[p].active == true) { winningVoteWeight = projects[p].votesWeight; _winningProject = projects[p].id; } } } // Activates voting // Clears projects function enableVoting() public onlyAdmin returns(uint ballotId){ require(votingActive == false); require(frozen == false); curentBallotId++; votingActive = true; delete projects; emit VotingOn(curentBallotId); return curentBallotId; } // Deactivates voting function disableVoting() public onlyAdmin returns(uint winner){ require(votingActive == true); require(frozen == false); votingActive = false; curentWinner = winningProject(); addWinner(curentWinner); emit VotingOff(curentWinner); return curentWinner; } // sqrt root func function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } ///////////////////////////////////////////B A L L O T//////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////// // NOM token emission functions /////////////////////////////////////////////////////////////////////////////////////////////////////// // Pays 1.00000000 from epoch_fund to KYC-passed user // Uses payout(), bitmask_check(), bitmask_add() // adds 4 to bitmask function pay1(address to) public onlyAdmin returns(bool success){ require(bitmask_check(to, 4) == false); uint new_amount = 100000000; payout(to,new_amount); bitmask_add(to, 4); return true; } // Pays .555666XX from epoch_fund to user approved phone; // Uses payout(), bitmask_check(), bitmask_add() // adds 2 to bitmask function pay055(address to) public onlyAdmin returns(bool success){ require(bitmask_check(to, 2) == false); uint new_amount = 55566600 + (block.timestamp%100); payout(to,new_amount); bitmask_add(to, 2); return true; } // Pays .555666XX from epoch_fund to KYC user in new epoch; // Uses payout(), bitmask_check(), bitmask_add() // adds 2 to bitmask function pay055loyal(address to) public onlyAdmin returns(bool success){ require(epoch > 1); require(bitmask_check(to, 4) == true); uint new_amount = 55566600 + (block.timestamp%100); payout(to,new_amount); return true; } // Pays random number from epoch_fund // Uses payout() function payCustom(address to, uint amount) public onlyOwner returns(bool success){ payout(to,amount); return true; } // Pays [amount] of money to [to] account from epoch_fund // Counts amount +30% +10% // Updating _totalSupply // Pays to balance and 2 funds // Refreshes dec[] // Emits event function payout(address to, uint amount) private returns (bool success){ require(to != address(0)); require(amount>=current_mul()); require(bitmask_check(to, 1024) == false); // banned == false require(frozen == false); //Update account balance updateAccount(to); //fix amount uint fixedAmount = fix_amount(amount); renewDec( accounts[to].balance, accounts[to].balance.add(fixedAmount) ); uint team_part = (fixedAmount/100)*10; uint dao_part = (fixedAmount/100)*30; uint total = fixedAmount.add(team_part).add(dao_part); epoch_fund = epoch_fund.sub(total); team_fund = team_fund.add(team_part); redenom_dao_fund = redenom_dao_fund.add(dao_part); accounts[to].balance = accounts[to].balance.add(fixedAmount); _totalSupply = _totalSupply.add(total); emit Transfer(address(0), to, fixedAmount); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////// // Withdraw amount from team_fund to given address function withdraw_team_fund(address to, uint amount) public onlyOwner returns(bool success){ require(amount <= team_fund); accounts[to].balance = accounts[to].balance.add(amount); team_fund = team_fund.sub(amount); return true; } // Withdraw amount from redenom_dao_fund to given address function withdraw_dao_fund(address to, uint amount) public onlyOwner returns(bool success){ require(amount <= redenom_dao_fund); accounts[to].balance = accounts[to].balance.add(amount); redenom_dao_fund = redenom_dao_fund.sub(amount); return true; } function freeze_contract() public onlyOwner returns(bool success){ require(frozen == false); frozen = true; return true; } function unfreeze_contract() public onlyOwner returns(bool success){ require(frozen == true); frozen = false; return true; } /////////////////////////////////////////////////////////////////////////////////////////////////////// // Run this on every change of user balance // Refreshes dec[] array // Takes initial and new ammount // while transaction must be called for each acc. function renewDec(uint initSum, uint newSum) internal returns(bool success){ if(round < 9){ uint tempInitSum = initSum; uint tempNewSum = newSum; uint cnt = 1; while( (tempNewSum > 0 || tempInitSum > 0) && cnt <= decimals ){ uint lastInitSum = tempInitSum%10; // 0.0000000 (0) tempInitSum = tempInitSum/10; // (0.0000000) 0 uint lastNewSum = tempNewSum%10; // 1.5556664 (5) tempNewSum = tempNewSum/10; // (1.5556664) 5 if(cnt >= round){ if(lastNewSum >= lastInitSum){ // If new is bigger dec[decimals-cnt] = dec[decimals-cnt].add(lastNewSum - lastInitSum); }else{ // If new is smaller dec[decimals-cnt] = dec[decimals-cnt].sub(lastInitSum - lastNewSum); } } cnt = cnt+1; } }//if(round < 9){ return true; } ////////////////////////////////////////// BITMASK ///////////////////////////////////////////////////// // Adding bit to bitmask // checks if already set function bitmask_add(address user, uint _bit) internal returns(bool success){ //todo privat? require(bitmask_check(user, _bit) == false); accounts[user].bitmask = accounts[user].bitmask.add(_bit); return true; } // Removes bit from bitmask // checks if already set function bitmask_rm(address user, uint _bit) internal returns(bool success){ require(bitmask_check(user, _bit) == true); accounts[user].bitmask = accounts[user].bitmask.sub(_bit); return true; } // Checks whether some bit is present in BM function bitmask_check(address user, uint _bit) internal view returns (bool status){ bool flag; accounts[user].bitmask & _bit == 0 ? flag = false : flag = true; return flag; } /////////////////////////////////////////////////////////////////////////////////////////////////////// function ban_user(address user) public onlyAdmin returns(bool success){ bitmask_add(user, 1024); return true; } function unban_user(address user) public onlyAdmin returns(bool success){ bitmask_rm(user, 1024); return true; } function is_banned(address user) public view onlyAdmin returns (bool result){ return bitmask_check(user, 1024); } /////////////////////////////////////////////////////////////////////////////////////////////////////// //Redenominates function redenominate() public onlyAdmin returns(uint current_round){ require(frozen == false); require(round<9); // Round must be < 9 // Deleting funds rest from TS _totalSupply = _totalSupply.sub( team_fund%mul[round] ).sub( redenom_dao_fund%mul[round] ).sub( dec[8-round]*mul[round-1] ); // Redenominating 3 vars: _totalSupply team_fund redenom_dao_fund _totalSupply = ( _totalSupply / mul[round] ) * mul[round]; team_fund = ( team_fund / mul[round] ) * mul[round]; // Redenominates team_fund redenom_dao_fund = ( redenom_dao_fund / mul[round] ) * mul[round]; // Redenominates redenom_dao_fund if(round>1){ // decimals burned in last round and not distributed uint superold = dec[(8-round)+1]; // Returning them to epoch_fund epoch_fund = epoch_fund.add(superold * mul[round-2]); dec[(8-round)+1] = 0; } if(round<8){ // if round between 1 and 7 uint unclimed = dec[8-round]; // total sum of burned decimal //[23,32,43,34,34,54,34, ->46<- ] uint total_current = dec[8-1-round]; // total sum of last active decimal //[23,32,43,34,34,54, ->34<-, 46] // security check if(total_current==0){ current_toadd = [0,0,0,0,0,0,0,0,0]; round++; return round; } // Counting amounts to add on every digit uint[9] memory numbers =[uint(1),2,3,4,5,6,7,8,9]; // uint[9] memory ke9 =[uint(0),0,0,0,0,0,0,0,0]; // uint[9] memory k2e9 =[uint(0),0,0,0,0,0,0,0,0]; // uint k05summ = 0; for (uint k = 0; k < ke9.length; k++) { ke9[k] = numbers[k]*1e9/total_current; if(k<5) k05summ += ke9[k]; } for (uint k2 = 5; k2 < k2e9.length; k2++) { k2e9[k2] = uint(ke9[k2])+uint(k05summ)*uint(weight[k2])/uint(100); } for (uint n = 5; n < current_toadd.length; n++) { current_toadd[n] = k2e9[n]*unclimed/10/1e9; } // current_toadd now contains all digits }else{ if(round==8){ // Returns last burned decimals to epoch_fund epoch_fund = epoch_fund.add(dec[0] * 10000000); //1e7 dec[0] = 0; } } round++; emit Redenomination(round); return round; } // Refresh user acc // Pays dividends if any function updateAccount(address account) public returns(uint new_balance){ require(frozen == false); require(round<=9); require(bitmask_check(account, 1024) == false); // banned == false if(round > accounts[account].lastRound){ if(round >1 && round <=8){ // Splits user bal by current multiplier uint tempDividedBalance = accounts[account].balance/current_mul(); // [1.5556663] 4 (r2) uint newFixedBalance = tempDividedBalance*current_mul(); // [1.55566630] (r2) uint lastActiveDigit = tempDividedBalance%10; // 1.555666 [3] 4 (r2) uint diff = accounts[account].balance - newFixedBalance; // 1.5556663 [4] (r2) if(diff > 0){ accounts[account].balance = newFixedBalance; emit Transfer(account, address(0), diff); } uint toBalance = 0; if(lastActiveDigit>0 && current_toadd[lastActiveDigit-1]>0){ toBalance = current_toadd[lastActiveDigit-1] * current_mul(); } if(toBalance > 0 && toBalance < dec[8-round+1]){ // Not enough renewDec( accounts[account].balance, accounts[account].balance.add(toBalance) ); emit Transfer(address(0), account, toBalance); // Refreshing dec arr accounts[account].balance = accounts[account].balance.add(toBalance); // Adding to ball dec[8-round+1] = dec[8-round+1].sub(toBalance); // Taking from burned decimal _totalSupply = _totalSupply.add(toBalance); // Add dividend to _totalSupply } accounts[account].lastRound = round; // Writting last round in wich user got dividends return accounts[account].balance; // returns new balance }else{ if( round == 9){ //100000000 = 9 mul (mul8) uint newBalance = fix_amount(accounts[account].balance); uint _diff = accounts[account].balance.sub(newBalance); if(_diff > 0){ renewDec( accounts[account].balance, newBalance ); accounts[account].balance = newBalance; emit Transfer(account, address(0), _diff); } accounts[account].lastRound = round; // Writting last round in wich user got dividends return accounts[account].balance; // returns new balance } } } } // Returns current multipl. based on round // Returns current multiplier based on round function current_mul() internal view returns(uint _current_mul){ return mul[round-1]; } // Removes burned values 123 -> 120 // Returns fixed function fix_amount(uint amount) public view returns(uint fixed_amount){ return ( amount / current_mul() ) * current_mul(); } // Returns rest function get_rest(uint amount) internal view returns(uint fixed_amount){ return amount % current_mul(); } // ------------------------------------------------------------------------ // ERC20 totalSupply: //------------------------------------------------------------------------- function totalSupply() public view returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // ERC20 balanceOf: Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return accounts[tokenOwner].balance; } // ------------------------------------------------------------------------ // ERC20 allowance: // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // ERC20 transfer: // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(frozen == false); require(to != address(0)); require(bitmask_check(to, 1024) == false); // banned == false //Fixing amount, deleting burned decimals tokens = fix_amount(tokens); // Checking if greater then 0 require(tokens>0); //Refreshing accs, payng dividends updateAccount(to); updateAccount(msg.sender); uint fromOldBal = accounts[msg.sender].balance; uint toOldBal = accounts[to].balance; accounts[msg.sender].balance = accounts[msg.sender].balance.sub(tokens); accounts[to].balance = accounts[to].balance.add(tokens); require(renewDec(fromOldBal, accounts[msg.sender].balance)); require(renewDec(toOldBal, accounts[to].balance)); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // ERC20 approve: // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(frozen == false); require(bitmask_check(msg.sender, 1024) == false); // banned == false allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // ERC20 transferFrom: // Transfer `tokens` from the `from` account to the `to` account // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(frozen == false); require(bitmask_check(to, 1024) == false); // banned == false updateAccount(from); updateAccount(to); uint fromOldBal = accounts[from].balance; uint toOldBal = accounts[to].balance; accounts[from].balance = accounts[from].balance.sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); accounts[to].balance = accounts[to].balance.add(tokens); require(renewDec(fromOldBal, accounts[from].balance)); require(renewDec(toOldBal, accounts[to].balance)); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { require(frozen == false); require(bitmask_check(msg.sender, 1024) == false); // banned == false allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH https://github.com/ConsenSys/Ethereum-Development-Best-Practices/wiki/Fallback-functions-and-the-fundamental-limitations-of-using-send()-in-Ethereum-&-Solidity // ------------------------------------------------------------------------ function () public payable { revert(); } // OR function() payable { } to accept ETH // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { require(frozen == false); return ERC20Interface(tokenAddress).transfer(owner, tokens); } } // &#169; Musqogees Tech 2018, Redenom ™
Writting last round in wich user got dividends
return accounts[account].balance;
2,274,768
[ 1, 4913, 1787, 1142, 3643, 316, 341, 1354, 729, 2363, 3739, 350, 5839, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 10792, 327, 9484, 63, 4631, 8009, 12296, 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 ]
// File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.21; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.21; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.21; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/Token.sol pragma solidity 0.4.23; /// @title Token /// @author Jose Perez - <[email protected]> /// @notice ERC20 token /// @dev The contract allows to perform a number of token sales in different periods in time. /// allowing participants in previous token sales to transfer tokens to other accounts. /// Additionally, token locking logic for KYC/AML compliance checking is supported. contract Token is StandardToken, Ownable { using SafeMath for uint256; string public constant name = "Nynja"; string public constant symbol = "NYN"; uint256 public constant decimals = 18; // Using same number of decimal figures as ETH (i.e. 18). uint256 public constant TOKEN_UNIT = 10 ** uint256(decimals); // Maximum number of tokens in circulation uint256 public constant MAX_TOKEN_SUPPLY = 5000000000 * TOKEN_UNIT; // Maximum number of tokens sales to be performed. uint256 public constant MAX_TOKEN_SALES = 5; // Maximum size of the batch functions input arrays. uint256 public constant MAX_BATCH_SIZE = 400; address public assigner; // The address allowed to assign or mint tokens during token sale. address public locker; // The address allowed to lock/unlock addresses. mapping(address => bool) public locked; // If true, address' tokens cannot be transferred. uint256 public currentTokenSaleId = 0; // The id of the current token sale. mapping(address => uint256) public tokenSaleId; // In which token sale the address participated. bool public tokenSaleOngoing = false; event TokenSaleStarting(uint indexed tokenSaleId); event TokenSaleEnding(uint indexed tokenSaleId); event Lock(address indexed addr); event Unlock(address indexed addr); event Assign(address indexed to, uint256 amount); event Mint(address indexed to, uint256 amount); event LockerTransferred(address indexed previousLocker, address indexed newLocker); event AssignerTransferred(address indexed previousAssigner, address indexed newAssigner); /// @dev Constructor that initializes the contract. /// @param _assigner The assigner account. /// @param _locker The locker account. constructor(address _assigner, address _locker) public { require(_assigner != address(0)); require(_locker != address(0)); assigner = _assigner; locker = _locker; } /// @dev True if a token sale is ongoing. modifier tokenSaleIsOngoing() { require(tokenSaleOngoing); _; } /// @dev True if a token sale is not ongoing. modifier tokenSaleIsNotOngoing() { require(!tokenSaleOngoing); _; } /// @dev Throws if called by any account other than the assigner. modifier onlyAssigner() { require(msg.sender == assigner); _; } /// @dev Throws if called by any account other than the locker. modifier onlyLocker() { require(msg.sender == locker); _; } /// @dev Starts a new token sale. Only the owner can start a new token sale. If a token sale /// is ongoing, it has to be ended before a new token sale can be started. /// No more than `MAX_TOKEN_SALES` sales can be carried out. /// @return True if the operation was successful. function tokenSaleStart() external onlyOwner tokenSaleIsNotOngoing returns(bool) { require(currentTokenSaleId < MAX_TOKEN_SALES); currentTokenSaleId++; tokenSaleOngoing = true; emit TokenSaleStarting(currentTokenSaleId); return true; } /// @dev Ends the current token sale. Only the owner can end a token sale. /// @return True if the operation was successful. function tokenSaleEnd() external onlyOwner tokenSaleIsOngoing returns(bool) { emit TokenSaleEnding(currentTokenSaleId); tokenSaleOngoing = false; return true; } /// @dev Returns whether or not a token sale is ongoing. /// @return True if a token sale is ongoing. function isTokenSaleOngoing() external view returns(bool) { return tokenSaleOngoing; } /// @dev Getter of the variable `currentTokenSaleId`. /// @return Returns the current token sale id. function getCurrentTokenSaleId() external view returns(uint256) { return currentTokenSaleId; } /// @dev Getter of the variable `tokenSaleId[]`. /// @param _address The address of the participant. /// @return Returns the id of the token sale the address participated in. function getAddressTokenSaleId(address _address) external view returns(uint256) { return tokenSaleId[_address]; } /// @dev Allows the current owner to change the assigner. /// @param _newAssigner The address of the new assigner. /// @return True if the operation was successful. function transferAssigner(address _newAssigner) external onlyOwner returns(bool) { require(_newAssigner != address(0)); emit AssignerTransferred(assigner, _newAssigner); assigner = _newAssigner; return true; } /// @dev Function to mint tokens. It can only be called by the assigner during an ongoing token sale. /// @param _to The address that will receive the minted tokens. /// @param _amount The amount of tokens to mint. /// @return A boolean that indicates if the operation was successful. function mint(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) { totalSupply_ = totalSupply_.add(_amount); require(totalSupply_ <= MAX_TOKEN_SUPPLY); if (tokenSaleId[_to] == 0) { tokenSaleId[_to] = currentTokenSaleId; } require(tokenSaleId[_to] == currentTokenSaleId); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /// @dev Mints tokens for several addresses in one single call. /// @param _to address[] The addresses that get the tokens. /// @param _amount address[] The number of tokens to be minted. /// @return A boolean that indicates if the operation was successful. function mintInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) { require(_to.length > 0); require(_to.length == _amount.length); require(_to.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _to.length; i++) { mint(_to[i], _amount[i]); } return true; } /// @dev Function to assign any number of tokens to a given address. /// Compared to the `mint` function, the `assign` function allows not just to increase but also to decrease /// the number of tokens of an address by assigning a lower value than the address current balance. /// This function can only be executed during initial token sale. /// @param _to The address that will receive the assigned tokens. /// @param _amount The amount of tokens to assign. /// @return True if the operation was successful. function assign(address _to, uint256 _amount) public onlyAssigner tokenSaleIsOngoing returns(bool) { require(currentTokenSaleId == 1); // The desired value to assign (`_amount`) can be either higher or lower than the current number of tokens // of the address (`balances[_to]`). To calculate the new `totalSupply_` value, the difference between `_amount` // and `balances[_to]` (`delta`) is calculated first, and then added or substracted to `totalSupply_` accordingly. uint256 delta = 0; if (balances[_to] < _amount) { // balances[_to] will be increased, so totalSupply_ should be increased delta = _amount.sub(balances[_to]); totalSupply_ = totalSupply_.add(delta); } else { // balances[_to] will be decreased, so totalSupply_ should be decreased delta = balances[_to].sub(_amount); totalSupply_ = totalSupply_.sub(delta); } require(totalSupply_ <= MAX_TOKEN_SUPPLY); balances[_to] = _amount; tokenSaleId[_to] = currentTokenSaleId; emit Assign(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /// @dev Assigns tokens to several addresses in one call. /// @param _to address[] The addresses that get the tokens. /// @param _amount address[] The number of tokens to be assigned. /// @return True if the operation was successful. function assignInBatches(address[] _to, uint256[] _amount) external onlyAssigner tokenSaleIsOngoing returns(bool) { require(_to.length > 0); require(_to.length == _amount.length); require(_to.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _to.length; i++) { assign(_to[i], _amount[i]); } return true; } /// @dev Allows the current owner to change the locker. /// @param _newLocker The address of the new locker. /// @return True if the operation was successful. function transferLocker(address _newLocker) external onlyOwner returns(bool) { require(_newLocker != address(0)); emit LockerTransferred(locker, _newLocker); locker = _newLocker; return true; } /// @dev Locks an address. A locked address cannot transfer its tokens or other addresses' tokens out. /// Only addresses participating in the current token sale can be locked. /// Only the locker account can lock addresses and only during the token sale. /// @param _address address The address to lock. /// @return True if the operation was successful. function lockAddress(address _address) public onlyLocker tokenSaleIsOngoing returns(bool) { require(tokenSaleId[_address] == currentTokenSaleId); require(!locked[_address]); locked[_address] = true; emit Lock(_address); return true; } /// @dev Unlocks an address so that its owner can transfer tokens out again. /// Addresses can be unlocked any time. Only the locker account can unlock addresses /// @param _address address The address to unlock. /// @return True if the operation was successful. function unlockAddress(address _address) public onlyLocker returns(bool) { require(locked[_address]); locked[_address] = false; emit Unlock(_address); return true; } /// @dev Locks several addresses in one single call. /// @param _addresses address[] The addresses to lock. /// @return True if the operation was successful. function lockInBatches(address[] _addresses) external onlyLocker returns(bool) { require(_addresses.length > 0); require(_addresses.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _addresses.length; i++) { lockAddress(_addresses[i]); } return true; } /// @dev Unlocks several addresses in one single call. /// @param _addresses address[] The addresses to unlock. /// @return True if the operation was successful. function unlockInBatches(address[] _addresses) external onlyLocker returns(bool) { require(_addresses.length > 0); require(_addresses.length <= MAX_BATCH_SIZE); for (uint i = 0; i < _addresses.length; i++) { unlockAddress(_addresses[i]); } return true; } /// @dev Checks whether or not the given address is locked. /// @param _address address The address to be checked. /// @return Boolean indicating whether or not the address is locked. function isLocked(address _address) external view returns(bool) { return locked[_address]; } /// @dev Transfers tokens to the specified address. It prevents transferring tokens from a locked address. /// Locked addresses can receive tokens. /// Current token sale's addresses cannot receive or send tokens until the token sale ends. /// @param _to The address to transfer tokens to. /// @param _value The number of tokens to be transferred. function transfer(address _to, uint256 _value) public returns(bool) { require(!locked[msg.sender]); if (tokenSaleOngoing) { require(tokenSaleId[msg.sender] < currentTokenSaleId); require(tokenSaleId[_to] < currentTokenSaleId); } return super.transfer(_to, _value); } /// @dev Transfers tokens from one address to another. It prevents transferring tokens if the caller is locked or /// if the allowed address is locked. /// Locked addresses can receive tokens. /// Current token sale's addresses cannot receive or send tokens until the token sale ends. /// @param _from address The address to transfer tokens from. /// @param _to address The address to transfer tokens to. /// @param _value The number of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!locked[msg.sender]); require(!locked[_from]); if (tokenSaleOngoing) { require(tokenSaleId[msg.sender] < currentTokenSaleId); require(tokenSaleId[_from] < currentTokenSaleId); require(tokenSaleId[_to] < currentTokenSaleId); } return super.transferFrom(_from, _to, _value); } }
@dev Unlocks an address so that its owner can transfer tokens out again. Addresses can be unlocked any time. Only the locker account can unlock addresses @param _address address The address to unlock. @return True if the operation was successful.
function unlockAddress(address _address) public onlyLocker returns(bool) { require(locked[_address]); locked[_address] = false; emit Unlock(_address); return true; }
12,685,521
[ 1, 7087, 87, 392, 1758, 1427, 716, 2097, 3410, 848, 7412, 2430, 596, 3382, 18, 1377, 23443, 848, 506, 25966, 1281, 813, 18, 5098, 326, 28152, 2236, 848, 7186, 6138, 225, 389, 2867, 1758, 1021, 1758, 358, 7186, 18, 327, 1053, 309, 326, 1674, 1703, 6873, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7186, 1887, 12, 2867, 389, 2867, 13, 1071, 1338, 2531, 264, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 12, 15091, 63, 67, 2867, 19226, 203, 203, 3639, 8586, 63, 67, 2867, 65, 273, 629, 31, 203, 3639, 3626, 3967, 24899, 2867, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.15; pragma experimental ABIEncoderV2; import { ParamManager } from "./libs/ParamManager.sol"; import { Governance } from "./Governance.sol"; import { NameRegistry as Registry } from "./NameRegistry.sol"; contract MerkleTreeUtils { // The default hashes bytes32[] public defaultHashes; uint256 public MAX_DEPTH; Governance public governance; /** * @notice Initialize a new MerkleTree contract, computing the default hashes for the merkle tree (MT) */ constructor(address _registryAddr) public { Registry nameRegistry = Registry(_registryAddr); governance = Governance( nameRegistry.getContractDetails(ParamManager.Governance()) ); MAX_DEPTH = governance.MAX_DEPTH(); defaultHashes = new bytes32[](MAX_DEPTH); // Calculate & set the default hashes setDefaultHashes(MAX_DEPTH); } /* Methods */ /** * @notice Set default hashes */ function setDefaultHashes(uint256 depth) internal { // Set the initial default hash. defaultHashes[0] = keccak256(abi.encode(0)); for (uint256 i = 1; i < depth; i++) { defaultHashes[i] = keccak256( abi.encode(defaultHashes[i - 1], defaultHashes[i - 1]) ); } } function getZeroRoot() public view returns (bytes32) { return keccak256( abi.encode( defaultHashes[MAX_DEPTH - 1], defaultHashes[MAX_DEPTH - 1] ) ); } function getMaxTreeDepth() public view returns (uint256) { return MAX_DEPTH; } function getRoot(uint256 index) public view returns (bytes32) { return defaultHashes[index]; } function getDefaultHashAtLevel(uint256 index) public view returns (bytes32) { return defaultHashes[index]; } function keecakHash(bytes memory data) public pure returns (bytes32) { return keccak256(data); } /** * @notice Get the merkle root computed from some set of data blocks. * @param _dataBlocks The data being used to generate the tree. * @return the merkle tree root * NOTE: This is a stateless operation */ function getMerkleRoot(bytes[] calldata _dataBlocks) external view returns (bytes32) { uint256 nextLevelLength = _dataBlocks.length; uint256 currentLevel = 0; bytes32[] memory nodes = new bytes32[](nextLevelLength + 1); // Add one in case we have an odd number of leaves // Generate the leaves for (uint256 i = 0; i < _dataBlocks.length; i++) { nodes[i] = keccak256(_dataBlocks[i]); } if (_dataBlocks.length == 1) { return nodes[0]; } // Add a defaultNode if we've got an odd number of leaves if (nextLevelLength % 2 == 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } // Now generate each level while (nextLevelLength > 1) { currentLevel += 1; // Calculate the nodes for the currentLevel for (uint256 i = 0; i < nextLevelLength / 2; i++) { nodes[i] = getParent(nodes[i * 2], nodes[i * 2 + 1]); } nextLevelLength = nextLevelLength / 2; // Check if we will need to add an extra node if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } } // Alright! We should be left with a single node! Return it... return nodes[0]; } /** * @notice Get the merkle root computed from some set of data blocks. * @param nodes The data being used to generate the tree. * @return the merkle tree root * NOTE: This is a stateless operation */ function getMerkleRootFromLeaves(bytes32[] memory nodes) public view returns (bytes32) { uint256 nextLevelLength = nodes.length; uint256 currentLevel = 0; if (nodes.length == 1) { return nodes[0]; } // Add a defaultNode if we've got an odd number of leaves if (nextLevelLength % 2 == 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } // Now generate each level while (nextLevelLength > 1) { currentLevel += 1; // Calculate the nodes for the currentLevel for (uint256 i = 0; i < nextLevelLength / 2; i++) { nodes[i] = getParent(nodes[i * 2], nodes[i * 2 + 1]); } nextLevelLength = nextLevelLength / 2; // Check if we will need to add an extra node if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } } // Alright! We should be left with a single node! Return it... return nodes[0]; } /** * @notice Calculate root from an inclusion proof. * @param _dataBlock The data block we're calculating root for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree * NOTE: This is a stateless operation */ function computeInclusionProofRoot( bytes memory _dataBlock, uint256 _path, bytes32[] memory _siblings ) public pure returns (bytes32) { // First compute the leaf node bytes32 computedNode = keccak256(_dataBlock); for (uint256 i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; uint8 isComputedRightSibling = getNthBitFromRight(_path, i); if (isComputedRightSibling == 0) { computedNode = getParent(computedNode, sibling); } else { computedNode = getParent(sibling, computedNode); } } // Check if the computed node (_root) is equal to the provided root return computedNode; } /** * @notice Calculate root from an inclusion proof. * @param _leaf The data block we're calculating root for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree * NOTE: This is a stateless operation */ function computeInclusionProofRootWithLeaf( bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) public pure returns (bytes32) { // First compute the leaf node bytes32 computedNode = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { bytes32 sibling = _siblings[i]; uint8 isComputedRightSibling = getNthBitFromRight(_path, i); if (isComputedRightSibling == 0) { computedNode = getParent(computedNode, sibling); } else { computedNode = getParent(sibling, computedNode); } } // Check if the computed node (_root) is equal to the provided root return computedNode; } /** * @notice Verify an inclusion proof. * @param _root The root of the tree we are verifying inclusion for. * @param _dataBlock The data block we're verifying inclusion for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree * NOTE: This is a stateless operation */ function verify( bytes32 _root, bytes memory _dataBlock, uint256 _path, bytes32[] memory _siblings ) public pure returns (bool) { // First compute the leaf node bytes32 calculatedRoot = computeInclusionProofRoot( _dataBlock, _path, _siblings ); return calculatedRoot == _root; } /** * @notice Verify an inclusion proof. * @param _root The root of the tree we are verifying inclusion for. * @param _leaf The data block we're verifying inclusion for. * @param _path The path from the leaf to the root. * @param _siblings The sibling nodes along the way. * @return The next level of the tree * NOTE: This is a stateless operation */ function verifyLeaf( bytes32 _root, bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) public pure returns (bool) { bytes32 calculatedRoot = computeInclusionProofRootWithLeaf( _leaf, _path, _siblings ); return calculatedRoot == _root; } /** * @notice Update a leaf using siblings and root * This is a stateless operation * @param _leaf The leaf we're updating. * @param _path The path from the leaf to the root / the index of the leaf. * @param _siblings The sibling nodes along the way. * @return Updated root */ function updateLeafWithSiblings( bytes32 _leaf, uint256 _path, bytes32[] memory _siblings ) public pure returns (bytes32) { bytes32 computedNode = _leaf; for (uint256 i = 0; i < _siblings.length; i++) { bytes32 parent; bytes32 sibling = _siblings[i]; uint8 isComputedRightSibling = getNthBitFromRight(_path, i); if (isComputedRightSibling == 0) { parent = getParent(computedNode, sibling); } else { parent = getParent(sibling, computedNode); } computedNode = parent; } return computedNode; } /** * @notice Get the parent of two children nodes in the tree * @param _left The left child * @param _right The right child * @return The parent node */ function getParent(bytes32 _left, bytes32 _right) public pure returns (bytes32) { return keccak256(abi.encode(_left, _right)); } /** * @notice get the n'th bit in a uint. * For instance, if exampleUint=binary(11), getNth(exampleUint, 0) == 1, getNth(2, 1) == 1 * @param _intVal The uint we are extracting a bit out of * @param _index The index of the bit we want to extract * @return The bit (1 or 0) in a uint8 */ function getNthBitFromRight(uint256 _intVal, uint256 _index) public pure returns (uint8) { return uint8((_intVal >> _index) & 1); } /** * @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash to signify if it is on the right side of the parent or on the left * @param _parent The parent node * @return the key for the left sibling (0 as the first bit) */ function getLeftSiblingKey(bytes32 _parent) public pure returns (bytes32) { return _parent & 0x0111111111111111111111111111111111111111111111111111111111111111; } /** * @notice Get the right sibling key. Note that these keys overwrite the first bit of the hash to signify if it is on the right side of the parent or on the left * @param _parent The parent node * @return the key for the right sibling (1 as the first bit) */ function getRightSiblingKey(bytes32 _parent) public pure returns (bytes32) { return _parent | 0x1000000000000000000000000000000000000000000000000000000000000000; } function pathToIndex(uint256 path, uint256 height) public pure returns (uint256) { uint256 result = 0; for (uint256 i = 0; i < height; i++) { uint8 temp = getNthBitFromRight(path, i); // UNSAFE FIX THIS result = result + (temp * (2**i)); } return result; } }
* @notice Get the merkle root computed from some set of data blocks. @param nodes The data being used to generate the tree. @return the merkle tree root NOTE: This is a stateless operation/ Add a defaultNode if we've got an odd number of leaves Now generate each level Calculate the nodes for the currentLevel Check if we will need to add an extra node
function getMerkleRootFromLeaves(bytes32[] memory nodes) public view returns (bytes32) { uint256 nextLevelLength = nodes.length; uint256 currentLevel = 0; if (nodes.length == 1) { return nodes[0]; } if (nextLevelLength % 2 == 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } while (nextLevelLength > 1) { currentLevel += 1; for (uint256 i = 0; i < nextLevelLength / 2; i++) { nodes[i] = getParent(nodes[i * 2], nodes[i * 2 + 1]); } nextLevelLength = nextLevelLength / 2; if (nextLevelLength % 2 == 1 && nextLevelLength != 1) { nodes[nextLevelLength] = defaultHashes[currentLevel]; nextLevelLength += 1; } } }
14,098,910
[ 1, 967, 326, 30235, 1365, 8470, 628, 2690, 444, 434, 501, 4398, 18, 225, 2199, 1021, 501, 3832, 1399, 358, 2103, 326, 2151, 18, 327, 326, 30235, 2151, 1365, 5219, 30, 1220, 353, 279, 610, 12617, 1674, 19, 1436, 279, 805, 907, 309, 732, 8081, 2363, 392, 14800, 1300, 434, 15559, 4494, 2103, 1517, 1801, 9029, 326, 2199, 364, 326, 783, 2355, 2073, 309, 732, 903, 1608, 358, 527, 392, 2870, 756, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 30040, 15609, 2375, 1265, 1682, 6606, 12, 3890, 1578, 8526, 3778, 2199, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 2254, 5034, 1024, 2355, 1782, 273, 2199, 18, 2469, 31, 203, 3639, 2254, 5034, 783, 2355, 273, 374, 31, 203, 3639, 309, 261, 4690, 18, 2469, 422, 404, 13, 288, 203, 5411, 327, 2199, 63, 20, 15533, 203, 3639, 289, 203, 203, 3639, 309, 261, 4285, 2355, 1782, 738, 576, 422, 404, 13, 288, 203, 5411, 2199, 63, 4285, 2355, 1782, 65, 273, 805, 14455, 63, 2972, 2355, 15533, 203, 5411, 1024, 2355, 1782, 1011, 404, 31, 203, 3639, 289, 203, 203, 3639, 1323, 261, 4285, 2355, 1782, 405, 404, 13, 288, 203, 5411, 783, 2355, 1011, 404, 31, 203, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1024, 2355, 1782, 342, 576, 31, 277, 27245, 288, 203, 7734, 2199, 63, 77, 65, 273, 5089, 12, 4690, 63, 77, 380, 576, 6487, 2199, 63, 77, 380, 576, 397, 404, 19226, 203, 5411, 289, 203, 203, 5411, 1024, 2355, 1782, 273, 1024, 2355, 1782, 342, 576, 31, 203, 5411, 309, 261, 4285, 2355, 1782, 738, 576, 422, 404, 597, 1024, 2355, 1782, 480, 404, 13, 288, 203, 7734, 2199, 63, 4285, 2355, 1782, 65, 273, 805, 14455, 63, 2972, 2355, 15533, 203, 7734, 1024, 2355, 1782, 1011, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x327340BB260172C3AFd97dEC3877Dc11271523c2/sources/project_/contracts/NFTCollection.sol
Set the base URI Suffix
string baseURISuffix = ".json";
1,869,909
[ 1, 694, 326, 1026, 3699, 348, 2609, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 533, 1026, 3098, 5791, 273, 3552, 1977, 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, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xE058A8Ed175911823e347B6310Cb4EC672d81201/sources/project:/contracts/source/tokens/ERC721/CryptopiaERC721.sol
@title Cryptopia ERC721 @notice Non-fungible token that extends Openzeppelin ERC721 @dev Implements the ERC721 standard @author HFB - <[email protected]>
abstract contract CryptopiaERC721 is ICryptopiaERC721, ERC721EnumerableUpgradeable, ContextMixin, NativeMetaTransaction, OwnableUpgradeable, AccessControlUpgradeable, TokenRetriever { string public contractURI; string public baseTokenURI; IAuthenticator public authenticator; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); function __CryptopiaERC721_init( string memory _name, string memory _symbol, address _authenticator, string memory _initialContractURI, string memory _initialBaseTokenURI) internal onlyInitializing pragma solidity ^0.8.12 < 0.9.0; { __Ownable_init(); __AccessControl_init(); __EIP712_init(_name); __ERC721_init(_name, _symbol); __ERC721Enumerable_init_unchained(); __CryptopiaERC721_init_unchained( _authenticator, _initialContractURI, _initialBaseTokenURI); } function __CryptopiaERC721_init_unchained( address _authenticator, string memory initialContractURI, string memory initialBaseTokenURI) internal onlyInitializing { authenticator = IAuthenticator(_authenticator); contractURI = initialContractURI; baseTokenURI = initialBaseTokenURI; _grantRole(ADMIN_ROLE, msg.sender); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } function setContractURI(string memory uri) public virtual onlyRole(ADMIN_ROLE) { contractURI = uri; } function setBaseTokenURI(string memory uri) public virtual onlyRole(ADMIN_ROLE) { baseTokenURI = uri; } function tokenURI(uint tokenId) public override view returns (string memory) { return string(abi.encodePacked(baseTokenURI, StringsUpgradeable.toString(tokenId))); } function isApprovedOrOwner(address spender, uint256 tokenId) public override view returns (bool) { return _isApprovedOrOwner(spender, tokenId); } function isApprovedForAll(address owner, address operator) public override(ERC721Upgradeable, IERC721Upgradeable) view returns (bool) { if (authenticator.authenticate(operator)) { } return super.isApprovedForAll(owner, operator); } function isApprovedForAll(address owner, address operator) public override(ERC721Upgradeable, IERC721Upgradeable) view returns (bool) { if (authenticator.authenticate(operator)) { } return super.isApprovedForAll(owner, operator); } function retrieveTokens(IERC20Upgradeable tokenContract) public virtual override onlyRole(ADMIN_ROLE) { super.retrieveTokens(tokenContract); } function retrieveETH() public virtual onlyRole(ADMIN_ROLE) { require(success, "Failed to retrieve ETH"); } (bool success, ) = msg.sender.call{value: address(this).balance}(""); function supportsInterface(bytes4 interfaceId) override(ERC721EnumerableUpgradeable, AccessControlUpgradeable) public virtual view returns (bool) { return super.supportsInterface(interfaceId); } function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } }
1,956,911
[ 1, 22815, 556, 1155, 4232, 39, 27, 5340, 225, 3858, 17, 12125, 75, 1523, 1147, 716, 3231, 3502, 94, 881, 84, 292, 267, 4232, 39, 27, 5340, 225, 29704, 326, 4232, 39, 27, 5340, 4529, 225, 670, 22201, 300, 411, 4840, 2304, 36, 22784, 556, 1155, 18, 832, 34, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17801, 6835, 22752, 556, 1155, 654, 39, 27, 5340, 353, 467, 22815, 556, 1155, 654, 39, 27, 5340, 16, 4232, 39, 27, 5340, 3572, 25121, 10784, 429, 16, 1772, 14439, 16, 16717, 2781, 3342, 16, 14223, 6914, 10784, 429, 16, 24349, 10784, 429, 16, 3155, 30801, 288, 203, 203, 565, 533, 1071, 6835, 3098, 31, 203, 565, 533, 1071, 1026, 1345, 3098, 31, 203, 203, 565, 467, 18977, 1071, 17595, 31, 203, 203, 203, 565, 1731, 1578, 1071, 5381, 25969, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 15468, 67, 16256, 8863, 203, 203, 203, 565, 445, 1001, 22815, 556, 1155, 654, 39, 27, 5340, 67, 2738, 12, 203, 3639, 533, 3778, 389, 529, 16, 7010, 3639, 533, 3778, 389, 7175, 16, 7010, 3639, 1758, 389, 1944, 10149, 16, 21281, 3639, 533, 3778, 389, 6769, 8924, 3098, 16, 7010, 3639, 533, 3778, 389, 6769, 2171, 1345, 3098, 13, 7010, 3639, 2713, 1338, 29782, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2138, 411, 374, 18, 29, 18, 20, 31, 203, 565, 288, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 1001, 16541, 67, 2738, 5621, 203, 3639, 1001, 41, 2579, 27, 2138, 67, 2738, 24899, 529, 1769, 203, 3639, 1001, 654, 39, 27, 5340, 67, 2738, 24899, 529, 16, 389, 7175, 1769, 203, 3639, 1001, 654, 39, 27, 5340, 3572, 25121, 67, 2738, 67, 4384, 8707, 5621, 203, 3639, 1001, 22815, 556, 1155, 654, 39, 27, 5340, 67, 2738, 67, 4384, 8707, 12, 203, 5411, 389, 1944, 10149, 16, 7010, 2 ]
pragma solidity ^0.5.0; import "../installed_contracts/Ownable.sol"; import "../installed_contracts/Pausable.sol"; ///@title A personal virtual graveyard for beloved hamsters. ///@author Soth02 ///@notice Use this contract at your own risk! It has not been professionally audited for security. contract HamsterGraveyard is Ownable, Pausable { /// Create a variable to keep track of the hamsterGrave ID numbers. uint public idGenerator = 0; /// this is the main data structure for instantiated a single hamster memorial. The front end UI will display this information. struct HamsterGrave { string name; /// should validate these for valid years. This input validation can be done on the front end as well. uint yearOfBirth; uint yearOfDeath; /// limit memorium to 100 characters. Might have to do this on front end? string memoriam; bool isCreated; } /// graves is an mapping of HamsterGrave structs mapping (uint => HamsterGrave) public graves; ///events ///@dev event to log addHamsterGrave results event LogHamsterGraveAdded(uint hamsterGraveNum, string name, uint yearOfBirth, uint yearOfDeath, string memoriam); ///@dev event to log updateHamsterGrave results event LogHamsterGraveUpdated(uint hamsterGraveNum, string name, uint yearOfBirth, uint yearOfDeath, string memoriam); ///@dev get idGenerator ///@return idGenerator - current value represents the (max value of the used uint keys)+1 function getIdGenerator() view public returns (uint){ return (idGenerator); } ///@dev allows the owner to add new memorials ///@param name - Name of the dead hamster ///@param yearOfBirth - year hamster was born ///@param yearOfDeath - year hamster died ///@param memoriam - memoriam the user would like to give their hamster ///@return uint of the grave's id function addHamsterGrave (string memory name, uint yearOfBirth, uint yearOfDeath, string memory memoriam ) public whenNotPaused() onlyOwner() returns (uint) { require(yearOfDeath >= yearOfBirth); graves[idGenerator].isCreated = true; graves[idGenerator].name = name; graves[idGenerator].yearOfBirth = yearOfBirth; graves[idGenerator].yearOfDeath = yearOfDeath; graves[idGenerator].memoriam = memoriam; emit LogHamsterGraveAdded(idGenerator, name, yearOfBirth, yearOfDeath, memoriam); idGenerator += 1; return (idGenerator-1); } ///@dev allows the owner to update their hamster info ///@param name - Name of the dead hamster ///@param yearOfBirth - year hamster was born ///@param yearOfDeath - year hamster died ///@param memoriam - memoriam the user would like to give their hamster ///@return uint of the grave's id function updateHamsterGrave (uint hamsterGraveNum, string memory name, uint yearOfBirth, uint yearOfDeath, string memory memoriam ) public whenNotPaused() onlyOwner() returns (uint) { graves[hamsterGraveNum].name = name; graves[hamsterGraveNum].yearOfBirth = yearOfBirth; graves[hamsterGraveNum].yearOfDeath = yearOfDeath; graves[hamsterGraveNum].memoriam = memoriam; emit LogHamsterGraveUpdated(hamsterGraveNum, name, yearOfBirth, yearOfDeath, memoriam); return (hamsterGraveNum); } ///@dev allows anyone to view the owner's hamster graveyard ///@param hamsterGraveNum - id of the hamster grave to view ///@return name, yearOfBirth, yearOfDeath, memoriam function viewHamsterGrave (uint hamsterGraveNum) view public returns (string memory name, uint yearOfBirth, uint yearOfDeath, string memory memoriam) { name = graves[hamsterGraveNum].name; yearOfBirth = graves[hamsterGraveNum].yearOfBirth; yearOfDeath = graves[hamsterGraveNum].yearOfDeath; memoriam = graves[hamsterGraveNum].memoriam; return(name, yearOfBirth, yearOfDeath, memoriam); } }
@dev allows anyone to view the owner's hamster graveyard@param hamsterGraveNum - id of the hamster grave to view@return name, yearOfBirth, yearOfDeath, memoriam
function viewHamsterGrave (uint hamsterGraveNum) view public returns (string memory name, uint yearOfBirth, uint yearOfDeath, string memory memoriam) { name = graves[hamsterGraveNum].name; yearOfBirth = graves[hamsterGraveNum].yearOfBirth; yearOfDeath = graves[hamsterGraveNum].yearOfDeath; memoriam = graves[hamsterGraveNum].memoriam; return(name, yearOfBirth, yearOfDeath, memoriam); }
5,401,215
[ 1, 5965, 87, 1281, 476, 358, 1476, 326, 3410, 1807, 366, 301, 8190, 3087, 9062, 1060, 366, 301, 8190, 14571, 537, 2578, 300, 612, 434, 326, 366, 301, 8190, 3087, 537, 358, 1476, 2463, 508, 16, 3286, 951, 25791, 16, 3286, 951, 758, 421, 16, 1663, 280, 29401, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1476, 44, 301, 8190, 14571, 537, 261, 11890, 366, 301, 8190, 14571, 537, 2578, 13, 1476, 1071, 203, 202, 225, 1135, 261, 1080, 3778, 508, 16, 2254, 3286, 951, 25791, 16, 2254, 3286, 951, 758, 421, 16, 533, 3778, 1663, 280, 29401, 13, 288, 203, 203, 1377, 508, 273, 3087, 3324, 63, 31698, 8190, 14571, 537, 2578, 8009, 529, 31, 203, 1377, 3286, 951, 25791, 273, 3087, 3324, 63, 31698, 8190, 14571, 537, 2578, 8009, 6874, 951, 25791, 31, 203, 1377, 3286, 951, 758, 421, 273, 3087, 3324, 63, 31698, 8190, 14571, 537, 2578, 8009, 6874, 951, 758, 421, 31, 203, 1377, 1663, 280, 29401, 273, 3087, 3324, 63, 31698, 8190, 14571, 537, 2578, 8009, 3917, 280, 29401, 31, 203, 203, 1377, 327, 12, 529, 16, 3286, 951, 25791, 16, 3286, 951, 758, 421, 16, 1663, 280, 29401, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7c21F5114A6226900a68Df97ebbaE4863b594046/sources/contracts/Landing/LendingPool.sol
transferring the tokens in the end
token.transfer(user, _amount);
17,186,863
[ 1, 2338, 74, 20245, 326, 2430, 316, 326, 679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1147, 18, 13866, 12, 1355, 16, 389, 8949, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import './interfaces/IForceMove.sol'; import './interfaces/IForceMoveApp.sol'; /** * @dev An implementation of ForceMove protocol, which allows state channels to be adjudicated and finalized. */ contract ForceMove is IForceMove { mapping(bytes32 => bytes32) public statusOf; // Public methods: /** * @notice Unpacks turnNumRecord, finalizesAt and fingerprint from the status of a particular channel. * @dev Unpacks turnNumRecord, finalizesAt and fingerprint from the status of a particular channel. * @param channelId Unique identifier for a state channel. * @return turnNumRecord A turnNum that (the adjudicator knows) is supported by a signature from each participant. * @return finalizesAt The unix timestamp when `channelId` will finalize. * @return fingerprint The last 160 bits of kecca256(stateHash, challengerAddress, outcomeHash) */ function unpackStatus(bytes32 channelId) external view returns ( uint48 turnNumRecord, uint48 finalizesAt, uint160 fingerprint ) { (turnNumRecord, finalizesAt, fingerprint) = _unpackStatus(channelId); } /** * @notice Registers a challenge against a state channel. A challenge will either prompt another participant into clearing the challenge (via one of the other methods), or cause the channel to finalize at a specific time. * @dev Registers a challenge against a state channel. A challenge will either prompt another participant into clearing the challenge (via one of the other methods), or cause the channel to finalize at a specific time. * @param fixedPart Data describing properties of the state channel that do not change with state updates. * @param largestTurnNum The largest turn number of the submitted states; will overwrite the stored value of `turnNumRecord`. * @param variableParts An ordered array of structs, each decribing the properties of the state channel that may change with each state update. Length is from 1 to the number of participants (inclusive). * @param isFinalCount Describes how many of the submitted states have the `isFinal` property set to `true`. It is implied that the rightmost `isFinalCount` states are final, and the rest are not final. * @param sigs An array of signatures that support the state with the `largestTurnNum`. There must be one for each participant, e.g.: [sig-from-p0, sig-from-p1, ...] * @param whoSignedWhat An array denoting which participant has signed which state: `participant[i]` signed the state with index `whoSignedWhat[i]`. * @param challengerSig The signature of a participant on the keccak256 of the abi.encode of (supportedStateHash, 'forceMove'). */ function challenge( FixedPart memory fixedPart, uint48 largestTurnNum, IForceMoveApp.VariablePart[] memory variableParts, uint8 isFinalCount, // how many of the states are final Signature[] memory sigs, uint8[] memory whoSignedWhat, Signature memory challengerSig ) external override { // input type validation requireValidInput( fixedPart.participants.length, variableParts.length, sigs.length, whoSignedWhat.length ); bytes32 channelId = _getChannelId(fixedPart); if (_mode(channelId) == ChannelMode.Open) { _requireNonDecreasedTurnNumber(channelId, largestTurnNum); } else if (_mode(channelId) == ChannelMode.Challenge) { _requireIncreasedTurnNumber(channelId, largestTurnNum); } else { // This should revert. _requireChannelNotFinalized(channelId); } bytes32 supportedStateHash = _requireStateSupportedBy( largestTurnNum, variableParts, isFinalCount, channelId, fixedPart, sigs, whoSignedWhat ); address challenger = _requireChallengerIsParticipant( supportedStateHash, fixedPart.participants, challengerSig ); // effects emit ChallengeRegistered( channelId, largestTurnNum, uint48(block.timestamp) + fixedPart.challengeDuration, //solhint-disable-line not-rely-on-time // This could overflow, so don't join a channel with a huge challengeDuration challenger, isFinalCount > 0, fixedPart, variableParts, sigs, whoSignedWhat ); statusOf[channelId] = _generateStatus( ChannelData( largestTurnNum, uint48(block.timestamp) + fixedPart.challengeDuration, //solhint-disable-line not-rely-on-time supportedStateHash, challenger, keccak256(variableParts[variableParts.length - 1].outcome) ) ); } /** * @notice Repsonds to an ongoing challenge registered against a state channel. * @dev Repsonds to an ongoing challenge registered against a state channel. * @param challenger The address of the participant whom registered the challenge. * @param isFinalAB An pair of booleans describing if the challenge state and/or the response state have the `isFinal` property set to `true`. * @param fixedPart Data describing properties of the state channel that do not change with state updates. * @param variablePartAB An pair of structs, each decribing the properties of the state channel that may change with each state update (for the challenge state and for the response state). * @param sig The responder's signature on the `responseStateHash`. */ function respond( address challenger, bool[2] memory isFinalAB, FixedPart memory fixedPart, IForceMoveApp.VariablePart[2] memory variablePartAB, // variablePartAB[0] = challengeVariablePart // variablePartAB[1] = responseVariablePart Signature memory sig ) external override { // No need to validate fixedPart.participants.length here, as that validation would have happened during challenge bytes32 channelId = _getChannelId(fixedPart); (uint48 turnNumRecord, uint48 finalizesAt, ) = _unpackStatus(channelId); bytes32 challengeOutcomeHash = keccak256(variablePartAB[0].outcome); bytes32 responseOutcomeHash = keccak256(variablePartAB[1].outcome); bytes32 challengeStateHash = _hashState( turnNumRecord, isFinalAB[0], channelId, fixedPart, variablePartAB[0].appData, challengeOutcomeHash ); bytes32 responseStateHash = _hashState( turnNumRecord + 1, isFinalAB[1], channelId, fixedPart, variablePartAB[1].appData, responseOutcomeHash ); // checks _requireSpecificChallenge( ChannelData( turnNumRecord, finalizesAt, challengeStateHash, challenger, challengeOutcomeHash ), channelId ); require( _recoverSigner(responseStateHash, sig) == fixedPart.participants[(turnNumRecord + 1) % fixedPart.participants.length], 'Signer not authorized mover' ); _requireValidTransition( fixedPart.participants.length, isFinalAB, variablePartAB, turnNumRecord + 1, fixedPart.appDefinition ); // effects _clearChallenge(channelId, turnNumRecord + 1); } /** * @notice Overwrites the `turnNumRecord` stored against a channel by providing a state with higher turn number, supported by a signature from each participant. * @dev Overwrites the `turnNumRecord` stored against a channel by providing a state with higher turn number, supported by a signature from each participant. * @param fixedPart Data describing properties of the state channel that do not change with state updates. * @param largestTurnNum The largest turn number of the submitted states; will overwrite the stored value of `turnNumRecord`. * @param variableParts An ordered array of structs, each decribing the properties of the state channel that may change with each state update. * @param isFinalCount Describes how many of the submitted states have the `isFinal` property set to `true`. It is implied that the rightmost `isFinalCount` states are final, and the rest are not final. * @param sigs An array of signatures that support the state with the `largestTurnNum`. * @param whoSignedWhat An array denoting which participant has signed which state: `participant[i]` signed the state with index `whoSignedWhat[i]`. */ function checkpoint( FixedPart memory fixedPart, uint48 largestTurnNum, IForceMoveApp.VariablePart[] memory variableParts, uint8 isFinalCount, // how many of the states are final Signature[] memory sigs, uint8[] memory whoSignedWhat ) external override { // input type validation requireValidInput( fixedPart.participants.length, variableParts.length, sigs.length, whoSignedWhat.length ); bytes32 channelId = _getChannelId(fixedPart); // checks _requireChannelNotFinalized(channelId); _requireIncreasedTurnNumber(channelId, largestTurnNum); _requireStateSupportedBy( largestTurnNum, variableParts, isFinalCount, channelId, fixedPart, sigs, whoSignedWhat ); // effects _clearChallenge(channelId, largestTurnNum); } /** * @notice Finalizes a channel by providing a finalization proof. External wrapper for _conclude. * @dev Finalizes a channel by providing a finalization proof. External wrapper for _conclude. * @param largestTurnNum The largest turn number of the submitted states; will overwrite the stored value of `turnNumRecord`. * @param fixedPart Data describing properties of the state channel that do not change with state updates. * @param appPartHash The keccak256 of the abi.encode of `(challengeDuration, appDefinition, appData)`. Applies to all states in the finalization proof. * @param outcomeHash The keccak256 of the abi.encode of the `outcome`. Applies to all states in the finalization proof. * @param numStates The number of states in the finalization proof. * @param whoSignedWhat An array denoting which participant has signed which state: `participant[i]` signed the state with index `whoSignedWhat[i]`. * @param sigs An array of signatures that support the state with the `largestTurnNum`. */ function conclude( uint48 largestTurnNum, FixedPart memory fixedPart, bytes32 appPartHash, bytes32 outcomeHash, uint8 numStates, uint8[] memory whoSignedWhat, Signature[] memory sigs ) external override { _conclude( largestTurnNum, fixedPart, appPartHash, outcomeHash, numStates, whoSignedWhat, sigs ); } /** * @notice Finalizes a channel by providing a finalization proof. Internal method. * @dev Finalizes a channel by providing a finalization proof. Internal method. * @param largestTurnNum The largest turn number of the submitted states; will overwrite the stored value of `turnNumRecord`. * @param fixedPart Data describing properties of the state channel that do not change with state updates. * @param appPartHash The keccak256 of the abi.encode of `(challengeDuration, appDefinition, appData)`. Applies to all states in the finalization proof. * @param outcomeHash The keccak256 of the `outcome`. Applies to all stats in the finalization proof. * @param numStates The number of states in the finalization proof. * @param whoSignedWhat An array denoting which participant has signed which state: `participant[i]` signed the state with index `whoSignedWhat[i]`. * @param sigs An array of signatures that support the state with the `largestTurnNum`. */ function _conclude( uint48 largestTurnNum, FixedPart memory fixedPart, bytes32 appPartHash, bytes32 outcomeHash, uint8 numStates, uint8[] memory whoSignedWhat, Signature[] memory sigs ) internal returns (bytes32 channelId) { channelId = _getChannelId(fixedPart); _requireChannelNotFinalized(channelId); // input type validation requireValidInput( fixedPart.participants.length, numStates, sigs.length, whoSignedWhat.length ); require(largestTurnNum + 1 >= numStates, 'largestTurnNum too low'); // ^^ SW-C101: prevent underflow // By construction, the following states form a valid transition bytes32[] memory stateHashes = new bytes32[](numStates); for (uint48 i = 0; i < numStates; i++) { stateHashes[i] = keccak256( abi.encode( State( largestTurnNum + (i + 1) - numStates, // turnNum // ^^ SW-C101: It is not easy to use SafeMath here, since we are not using uint256s // Instead, we are protected by the require statement above true, // isFinal channelId, appPartHash, outcomeHash ) ) ); } // checks require( _validSignatures( largestTurnNum, fixedPart.participants, stateHashes, sigs, whoSignedWhat ), 'Invalid signatures / !isFinal' ); // effects statusOf[channelId] = _generateStatus( ChannelData(0, uint48(block.timestamp), bytes32(0), address(0), outcomeHash) //solhint-disable-line not-rely-on-time ); emit Concluded(channelId, uint48(block.timestamp)); //solhint-disable-line not-rely-on-time } // Internal methods: /** * @notice Checks that the challengerSignature was created by one of the supplied participants. * @dev Checks that the challengerSignature was created by one of the supplied participants. * @param supportedStateHash Forms part of the digest to be signed, along with the string 'forceMove'. * @param participants A list of addresses representing the participants of a channel. * @param challengerSignature The signature of a participant on the keccak256 of the abi.encode of (supportedStateHash, 'forceMove'). */ function _requireChallengerIsParticipant( bytes32 supportedStateHash, address[] memory participants, Signature memory challengerSignature ) internal pure returns (address challenger) { challenger = _recoverSigner( keccak256(abi.encode(supportedStateHash, 'forceMove')), challengerSignature ); require(_isAddressInArray(challenger, participants), 'Challenger is not a participant'); } /** * @notice Tests whether a given address is in a given array of addresses. * @dev Tests whether a given address is in a given array of addresses. * @param suspect A single address of interest. * @param addresses A line-up of possible perpetrators. * @return true if the address is in the array, false otherwise */ function _isAddressInArray(address suspect, address[] memory addresses) internal pure returns (bool) { for (uint256 i = 0; i < addresses.length; i++) { if (suspect == addresses[i]) { return true; } } return false; } /** * @notice Given an array of state hashes, checks the validity of the supplied signatures. Valid means there is a signature for each participant, either on the hash of the state for which they are a mover, or on the hash of a state that appears after that state in the array. * @dev Given an array of state hashes, checks the validity of the supplied signatures. Valid means there is a signature for each participant, either on the hash of the state for which they are a mover, or on the hash of a state that appears after that state in the array. * @param largestTurnNum The largest turn number of the submitted states; will overwrite the stored value of `turnNumRecord`. * @param participants A list of addresses representing the participants of a channel. * @param stateHashes Array of keccak256(State) submitted in support of a state, * @param sigs Array of Signatures, one for each participant * @param whoSignedWhat participant[i] signed stateHashes[whoSignedWhat[i]] * @return true if the signatures are valid, false otherwise */ function _validSignatures( uint48 largestTurnNum, address[] memory participants, bytes32[] memory stateHashes, Signature[] memory sigs, uint8[] memory whoSignedWhat // whoSignedWhat[i] is the index of the state in stateHashes that was signed by participants[i] ) internal pure returns (bool) { uint256 nParticipants = participants.length; uint256 nStates = stateHashes.length; require( _acceptableWhoSignedWhat(whoSignedWhat, largestTurnNum, nParticipants, nStates), 'Unacceptable whoSignedWhat array' ); for (uint256 i = 0; i < nParticipants; i++) { address signer = _recoverSigner(stateHashes[whoSignedWhat[i]], sigs[i]); if (signer != participants[i]) { return false; } } return true; } /** * @notice Given a declaration of which state in the support proof was signed by which participant, check if this declaration is acceptable. Acceptable means there is a signature for each participant, either on the hash of the state for which they are a mover, or on the hash of a state that appears after that state in the array. * @dev Given a declaration of which state in the support proof was signed by which participant, check if this declaration is acceptable. Acceptable means there is a signature for each participant, either on the hash of the state for which they are a mover, or on the hash of a state that appears after that state in the array. * @param whoSignedWhat participant[i] signed stateHashes[whoSignedWhat[i]] * @param largestTurnNum Largest turnNum of the support proof * @param nParticipants Number of participants in the channel * @param nStates Number of states in the support proof * @return true if whoSignedWhat is acceptable, false otherwise */ function _acceptableWhoSignedWhat( uint8[] memory whoSignedWhat, uint48 largestTurnNum, uint256 nParticipants, uint256 nStates ) internal pure returns (bool) { require(whoSignedWhat.length == nParticipants, '|whoSignedWhat|!=nParticipants'); for (uint256 i = 0; i < nParticipants; i++) { uint256 offset = (nParticipants + largestTurnNum - i) % nParticipants; // offset is the difference between the index of participant[i] and the index of the participant who owns the largesTurnNum state // the additional nParticipants in the dividend ensures offset always positive if (whoSignedWhat[i] + offset + 1 < nStates) { return false; } } return true; } /** * @notice Given a digest and ethereum digital signature, recover the signer * @dev Given a digest and digital signature, recover the signer * @param _d message digest * @param sig ethereum digital signature * @return signer */ function _recoverSigner(bytes32 _d, Signature memory sig) internal pure returns (address) { bytes32 prefixedHash = keccak256(abi.encodePacked('\x19Ethereum Signed Message:\n32', _d)); address a = ecrecover(prefixedHash, sig.v, sig.r, sig.s); require(a != address(0), 'Invalid signature'); return (a); } /** * @notice Check that the submitted data constitute a support proof. * @dev Check that the submitted data constitute a support proof. * @param largestTurnNum Largest turnNum of the support proof * @param variableParts Variable parts of the states in the support proof * @param isFinalCount How many of the states are final? The final isFinalCount states are implied final, the remainder are implied not final. * @param channelId Unique identifier for a channel. * @param fixedPart Fixed Part of the states in the support proof * @param sigs A signature from each participant. * @param whoSignedWhat participant[i] signed stateHashes[whoSignedWhat[i]] * @return The hash of the latest state in the proof, if supported, else reverts. */ function _requireStateSupportedBy( uint48 largestTurnNum, IForceMoveApp.VariablePart[] memory variableParts, uint8 isFinalCount, bytes32 channelId, FixedPart memory fixedPart, Signature[] memory sigs, uint8[] memory whoSignedWhat ) internal pure returns (bytes32) { bytes32[] memory stateHashes = _requireValidTransitionChain( largestTurnNum, variableParts, isFinalCount, channelId, fixedPart ); require( _validSignatures( largestTurnNum, fixedPart.participants, stateHashes, sigs, whoSignedWhat ), 'Invalid signatures' ); return stateHashes[stateHashes.length - 1]; } /** * @notice Check that the submitted states form a chain of valid transitions * @dev Check that the submitted states form a chain of valid transitions * @param largestTurnNum Largest turnNum of the support proof * @param variableParts Variable parts of the states in the support proof * @param isFinalCount How many of the states are final? The final isFinalCount states are implied final, the remainder are implied not final. * @param channelId Unique identifier for a channel. * @param fixedPart Fixed Part of the states in the support proof * @return true if every state is a validTransition from its predecessor, false otherwise. */ function _requireValidTransitionChain( // returns stateHashes array if valid // else, reverts uint48 largestTurnNum, IForceMoveApp.VariablePart[] memory variableParts, uint8 isFinalCount, bytes32 channelId, FixedPart memory fixedPart ) internal pure returns (bytes32[] memory) { bytes32[] memory stateHashes = new bytes32[](variableParts.length); uint48 firstFinalTurnNum = largestTurnNum - isFinalCount + 1; uint48 turnNum; for (uint48 i = 0; i < variableParts.length; i++) { turnNum = largestTurnNum - uint48(variableParts.length) + 1 + i; stateHashes[i] = _hashState( turnNum, turnNum >= firstFinalTurnNum, channelId, fixedPart, variableParts[i].appData, keccak256(variableParts[i].outcome) ); if (turnNum < largestTurnNum) { _requireValidTransition( fixedPart.participants.length, [turnNum >= firstFinalTurnNum, turnNum + 1 >= firstFinalTurnNum], [variableParts[i], variableParts[i + 1]], turnNum + 1, fixedPart.appDefinition ); } } return stateHashes; } enum IsValidTransition {True, NeedToCheckApp} /** * @notice Check that the submitted pair of states form a valid transition * @dev Check that the submitted pair of states form a valid transition * @param nParticipants Number of participants in the channel. transition * @param isFinalAB Pair of booleans denoting whether the first and second state (resp.) are final. * @param ab Variable parts of each of the pair of states * @param turnNumB turnNum of the later state of the pair * @return true if the later state is a validTransition from its predecessor, false otherwise. */ function _requireValidProtocolTransition( uint256 nParticipants, bool[2] memory isFinalAB, // [a.isFinal, b.isFinal] IForceMoveApp.VariablePart[2] memory ab, // [a,b] uint48 turnNumB ) internal pure returns (IsValidTransition) { // a separate check on the signatures for the submitted states implies that the following fields are equal for a and b: // chainId, participants, channelNonce, appDefinition, challengeDuration // and that the b.turnNum = a.turnNum + 1 if (isFinalAB[1]) { require(_bytesEqual(ab[1].outcome, ab[0].outcome), 'Outcome change verboten'); } else { require(!isFinalAB[0], 'isFinal retrograde'); if (turnNumB < 2 * nParticipants) { require(_bytesEqual(ab[1].outcome, ab[0].outcome), 'Outcome change forbidden'); require(_bytesEqual(ab[1].appData, ab[0].appData), 'appData change forbidden'); } else { return IsValidTransition.NeedToCheckApp; } } return IsValidTransition.True; } /** * @notice Check that the submitted pair of states form a valid transition * @dev Check that the submitted pair of states form a valid transition * @param nParticipants Number of participants in the channel. transition * @param isFinalAB Pair of booleans denoting whether the first and second state (resp.) are final. * @param ab Variable parts of each of the pair of states * @param turnNumB turnNum of the later state of the pair. * @param appDefinition Address of deployed contract containing application-specific validTransition function. * @return true if the later state is a validTransition from its predecessor, false otherwise. */ function _requireValidTransition( uint256 nParticipants, bool[2] memory isFinalAB, // [a.isFinal, b.isFinal] IForceMoveApp.VariablePart[2] memory ab, // [a,b] uint48 turnNumB, address appDefinition ) internal pure returns (bool) { IsValidTransition isValidProtocolTransition = _requireValidProtocolTransition( nParticipants, isFinalAB, // [a.isFinal, b.isFinal] ab, // [a,b] turnNumB ); if (isValidProtocolTransition == IsValidTransition.NeedToCheckApp) { require( IForceMoveApp(appDefinition).validTransition(ab[0], ab[1], turnNumB, nParticipants), 'Invalid ForceMoveApp Transition' ); } return true; } /** * @notice Check for equality of two byte strings * @dev Check for equality of two byte strings * @param _preBytes One bytes string * @param _postBytes The other bytes string * @return true if the bytes are identical, false otherwise. */ function _bytesEqual(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { // copied from https://www.npmjs.com/package/solidity-bytes-utils/v/0.1.1 bool success = true; /* solhint-disable no-inline-assembly */ assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } /* solhint-disable no-inline-assembly */ return success; } /** * @notice Clears a challenge by updating the turnNumRecord and resetting the remaining channel storage fields, and emits a ChallengeCleared event. * @dev Clears a challenge by updating the turnNumRecord and resetting the remaining channel storage fields, and emits a ChallengeCleared event. * @param channelId Unique identifier for a channel. * @param newTurnNumRecord New turnNumRecord to overwrite existing value */ function _clearChallenge(bytes32 channelId, uint48 newTurnNumRecord) internal { statusOf[channelId] = _generateStatus( ChannelData(newTurnNumRecord, 0, bytes32(0), address(0), bytes32(0)) ); emit ChallengeCleared(channelId, newTurnNumRecord); } /** * @notice Checks that the submitted turnNumRecord is strictly greater than the turnNumRecord stored on chain. * @dev Checks that the submitted turnNumRecord is strictly greater than the turnNumRecord stored on chain. * @param channelId Unique identifier for a channel. * @param newTurnNumRecord New turnNumRecord intended to overwrite existing value */ function _requireIncreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord) internal view { (uint48 turnNumRecord, , ) = _unpackStatus(channelId); require(newTurnNumRecord > turnNumRecord, 'turnNumRecord not increased.'); } /** * @notice Checks that the submitted turnNumRecord is greater than or equal to the turnNumRecord stored on chain. * @dev Checks that the submitted turnNumRecord is greater than or equal to the turnNumRecord stored on chain. * @param channelId Unique identifier for a channel. * @param newTurnNumRecord New turnNumRecord intended to overwrite existing value */ function _requireNonDecreasedTurnNumber(bytes32 channelId, uint48 newTurnNumRecord) internal view { (uint48 turnNumRecord, , ) = _unpackStatus(channelId); require(newTurnNumRecord >= turnNumRecord, 'turnNumRecord decreased.'); } /** * @notice Checks that a given ChannelData struct matches the challenge stored on chain, and that the channel is in Challenge mode. * @dev Checks that a given ChannelData struct matches the challenge stored on chain, and that the channel is in Challenge mode. * @param data A given ChannelData data structure. * @param channelId Unique identifier for a channel. */ function _requireSpecificChallenge(ChannelData memory data, bytes32 channelId) internal view { _requireMatchingStorage(data, channelId); _requireOngoingChallenge(channelId); } /** * @notice Checks that a given channel is in the Challenge mode. * @dev Checks that a given channel is in the Challenge mode. * @param channelId Unique identifier for a channel. */ function _requireOngoingChallenge(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.'); } /** * @notice Checks that a given channel is NOT in the Finalized mode. * @dev Checks that a given channel is in the Challenge mode. * @param channelId Unique identifier for a channel. */ function _requireChannelNotFinalized(bytes32 channelId) internal view { require(_mode(channelId) != ChannelMode.Finalized, 'Channel finalized.'); } /** * @notice Checks that a given channel is in the Finalized mode. * @dev Checks that a given channel is in the Challenge mode. * @param channelId Unique identifier for a channel. */ function _requireChannelFinalized(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Finalized, 'Channel not finalized.'); } /** * @notice Checks that a given channel is in the Open mode. * @dev Checks that a given channel is in the Challenge mode. * @param channelId Unique identifier for a channel. */ function _requireChannelOpen(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Open, 'Channel not open.'); } /** * @notice Checks that a given ChannelData struct matches the challenge stored on chain. * @dev Checks that a given ChannelData struct matches the challenge stored on chain. * @param data A given ChannelData data structure. * @param channelId Unique identifier for a channel. */ function _requireMatchingStorage(ChannelData memory data, bytes32 channelId) internal view { require(_matchesStatus(data, statusOf[channelId]), 'status(ChannelData)!=storage'); } /** * @notice Computes the ChannelMode for a given channelId. * @dev Computes the ChannelMode for a given channelId. * @param channelId Unique identifier for a channel. */ function _mode(bytes32 channelId) internal view returns (ChannelMode) { // Note that _unpackStatus(someRandomChannelId) returns (0,0,0), which is // correct when nobody has written to storage yet. (, uint48 finalizesAt, ) = _unpackStatus(channelId); if (finalizesAt == 0) { return ChannelMode.Open; // solhint-disable-next-line not-rely-on-time } else if (finalizesAt <= block.timestamp) { return ChannelMode.Finalized; } else { return ChannelMode.Challenge; } } /** * @notice Formats the input data for on chain storage. * @dev Formats the input data for on chain storage. * @param channelData ChannelData data. */ function _generateStatus(ChannelData memory channelData) internal pure returns (bytes32 status) { // The hash is constructed from left to right. uint256 result; uint16 cursor = 256; // Shift turnNumRecord 208 bits left to fill the first 48 bits result = uint256(channelData.turnNumRecord) << (cursor -= 48); // logical or with finalizesAt padded with 160 zeros to get the next 48 bits result |= (uint256(channelData.finalizesAt) << (cursor -= 48)); // logical or with the last 160 bits of the hash the remaining channelData fields // (we call this the fingerprint) result |= uint256( uint160( uint256( keccak256( abi.encode( channelData.stateHash, channelData.challengerAddress, channelData.outcomeHash ) ) ) ) ); status = bytes32(result); } /** * @notice Unpacks turnNumRecord, finalizesAt and fingerprint from the status of a particular channel. * @dev Unpacks turnNumRecord, finalizesAt and fingerprint from the status of a particular channel. * @param channelId Unique identifier for a state channel. * @return turnNumRecord A turnNum that (the adjudicator knows) is supported by a signature from each participant. * @return finalizesAt The unix timestamp when `channelId` will finalize. * @return fingerprint The last 160 bits of kecca256(stateHash, challengerAddress, outcomeHash) */ function _unpackStatus(bytes32 channelId) internal view returns ( uint48 turnNumRecord, uint48 finalizesAt, uint160 fingerprint ) { bytes32 status = statusOf[channelId]; uint16 cursor = 256; turnNumRecord = uint48(uint256(status) >> (cursor -= 48)); finalizesAt = uint48(uint256(status) >> (cursor -= 48)); fingerprint = uint160(uint256(status)); } /** * @notice Checks that a given ChannelData struct matches a supplied bytes32 when formatted for storage. * @dev Checks that a given ChannelData struct matches a supplied bytes32 when formatted for storage. * @param data A given ChannelData data structure. * @param s Some data in on-chain storage format. */ function _matchesStatus(ChannelData memory data, bytes32 s) internal pure returns (bool) { return _generateStatus(data) == s; } /** * @notice Computes the hash of the state corresponding to the input data. * @dev Computes the hash of the state corresponding to the input data. * @param turnNum Turn number * @param isFinal Is the state final? * @param channelId Unique identifier for the channel * @param fixedPart Part of the state that does not change * @param appData Application specific date * @param outcomeHash Hash of the outcome. * @return The stateHash */ function _hashState( uint48 turnNum, bool isFinal, bytes32 channelId, FixedPart memory fixedPart, bytes memory appData, bytes32 outcomeHash ) internal pure returns (bytes32) { return keccak256( abi.encode( State( turnNum, isFinal, channelId, keccak256( abi.encode( fixedPart.challengeDuration, fixedPart.appDefinition, appData ) ), outcomeHash ) ) ); } function getChainID() public pure returns (uint256) { uint256 id; /* solhint-disable no-inline-assembly */ assembly { id := chainid() } /* solhint-disable no-inline-assembly */ return id; } /** * @notice Computes the unique id of a channel. * @dev Computes the unique id of a channel. * @param fixedPart Part of the state that does not change * @return channelId */ function _getChannelId(FixedPart memory fixedPart) internal pure returns (bytes32 channelId) { require(fixedPart.chainId == getChainID(), 'Incorrect chainId'); channelId = keccak256( abi.encode(getChainID(), fixedPart.participants, fixedPart.channelNonce) ); } /** * @notice Validates input for several external methods. * @dev Validates input for several external methods. * @param numParticipants Length of the participants array * @param numStates Number of states submitted * @param numSigs Number of signatures submitted * @param numWhoSignedWhats whoSignedWhat.length */ function requireValidInput( uint256 numParticipants, uint256 numStates, uint256 numSigs, uint256 numWhoSignedWhats ) public pure returns (bool) { require((numParticipants >= numStates) && (numStates > 0), 'Insufficient or excess states'); require( (numSigs == numParticipants) && (numWhoSignedWhats == numParticipants), 'Bad |signatures|v|whoSignedWhat|' ); require(numParticipants <= type(uint8).max, 'Too many participants!'); // type(uint8).max = 2**8 - 1 = 255 // no more than 255 participants // max index for participants is 254 return true; } }
* @notice Checks that a given channel is in the Challenge mode. @dev Checks that a given channel is in the Challenge mode. @param channelId Unique identifier for a channel./
function _requireOngoingChallenge(bytes32 channelId) internal view { require(_mode(channelId) == ChannelMode.Challenge, 'No ongoing challenge.'); }
993,169
[ 1, 4081, 716, 279, 864, 1904, 353, 316, 326, 1680, 8525, 1965, 18, 225, 13074, 716, 279, 864, 1904, 353, 316, 326, 1680, 8525, 1965, 18, 225, 27709, 14584, 2756, 364, 279, 1904, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 6528, 1398, 8162, 18359, 12, 3890, 1578, 27709, 13, 2713, 1476, 288, 203, 3639, 2583, 24899, 3188, 12, 4327, 548, 13, 422, 5307, 2309, 18, 18359, 16, 296, 2279, 30542, 12948, 1093, 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 ]
pragma solidity ^0.4.24; import './DNSUtilLibrary.sol'; import './BidRegistry.sol'; import './DNSDataModel.sol'; import './DNSStates.sol'; import './DNSBid.sol'; contract DNSDappMaster is DNSUtilLibrary { // constructor constructor() public { dnsRegistryOwner = msg.sender; emit DnsNameCreatedEvent(msg.sender); } // map address to DNSDatModel (key: dnsNameOwner, value: DNSDataModel) mapping (bytes32 => DNSDataModel.DNSData) dnsNameDataModelMap; // mapping for name to corresponding bidRegistry for name // key: dnsNameOwner value: BidRegistry (contains all bids received for the owner) mapping (bytes32 => BidRegistry) bidRegistryMap; //pre-bid transaction-fees goes to contract creator address dnsRegistryOwner; //declare events event DnsNameCreatedEvent(address _dnsRegistryOwner); event EtherTransferredToDNSNameEvent(string _dnsName, uint _amount); event ReserveAttemptDNSNameEvent(string _dnsName , uint _reservationFees, address _reservedAddress); event ReserveDNSNameEvent(string _dnsName , uint _reservationFees, address _reservedAddress, bool _successfulRegistration); event BestBidRaiseEvent(address _bestBidderAddress, uint _bestBidPrice); event BidFinalizationEvent(string _dnsName, address sender, address bestBidderAddress, uint bestBidPrice); event DNSNameOwnershipReleaseEvent(string _dnsName); /** * verify for the validity of the DNSNameString */ function verifyName(string _dnsName) public view returns(bool _exists) { bytes32 dnsLookupName = toBytes32(_dnsName); return hasDNSOwner(dnsLookupName); } /** * verify if the DNSName has Owner */ function hasDNSOwner(bytes32 _dnsName) internal view returns (bool _nameExists) { return dnsNameDataModelMap[_dnsName].active; } /** * lookup for the owner of the DNSName */ function getOwnerName(string _dnsName) public view returns(address) { bytes32 dnsLookupName = toBytes32(_dnsName); require(hasDNSOwner(dnsLookupName)); return dnsNameDataModelMap[dnsLookupName].nameOwner; } function checkForValidityOfDNSNameBid(uint _reservationFees) pure internal returns (bool) { bool isAValidFeesForReservation = true; if (_reservationFees < 1 finney) { isAValidFeesForReservation = false; } return isAValidFeesForReservation; } function transferEtherByDNSName(string _dnsName) public payable returns (bool) { //convert dnsName to Bytes bytes32 dnsLookupName = toBytes32(_dnsName); //check if the dnsName is valid require(hasDNSOwner(dnsLookupName)); uint funds = msg.value; //validate if the dnsNameOwner has sufficient balance require(msg.sender.balance > funds); //get Mapped dnsDataMpdel to local storage DNSDataModel.DNSData storage dnsName = dnsNameDataModelMap[dnsLookupName]; //validate that owner is not sending funds to self require(msg.sender != dnsName.nameOwner); dnsName.nameOwner.transfer(funds); emit EtherTransferredToDNSNameEvent(_dnsName,funds); return true; } /** * A new Bid placed * * This will have essential checks for bidding: * * 1. best-bid (highest price quoted) * 3. bidder is not same as name-owner * 3. name is a valid name (name exists in the registry) * */ function bidForDNSName(string _dnsName) public payable { bytes32 dnsNameLookupValue = toBytes32(_dnsName); // name should be owned by someone before you bid require(isAValidDNSName(dnsNameLookupValue)); // owner can't bid for his/her/it's name require(msg.sender != dnsNameDataModelMap[dnsNameLookupValue].nameOwner); //assert if the this is the highest bid received for this _dnsName require(msg.value > findTopBidPriceByDNSName(_dnsName)); BidRegistry bidRegistry = bidRegistryMap[dnsNameLookupValue]; uint bidPrice = msg.value; bidRegistry.makeNewBid(bidPrice,msg.sender); emit BestBidRaiseEvent(msg.sender,msg.value); } /** * find the best Bid Price for a dnsName * best bid is retrieved by accessing the bidRegistry of the dnsName * bidRegistry contains the indicativePrice / bestPrice of the dnsName */ function findTopBidPriceByDNSName(string _dnsName) public view returns (uint bidPrice){ //get bytes32 representation of the _dnsName bytes32 dnsLookupName = toBytes32(_dnsName); // lookup bidRegistry for this _dnsName BidRegistry bidRegistry = bidRegistryMap[dnsLookupName]; //bidRegistry contains bestPrice of all bids recorded for the _dnsName return bidRegistry.indicativePrice(); } //find the best-Bidder for a given DNSName from BidRegistry function findBestBidderAddressByDNSName(string _dnsName) public view returns(address bestBidderAddress) { //get bytes32 representation of the _dnsName bytes32 dnsName = toBytes32(_dnsName); // find the BidContainer for this name BidRegistry bidRegistry = bidRegistryMap[dnsName]; //return bestBidder's address from bidRegistry return bidRegistry.bestBidder(); } /** * DNSName-Owner selects and finalizes the bestBid * Ownership of the DNSName is transferred to the bestBidder's address * Best-Bidder's funds are transferred to the current owner of the DNSName */ function finalizeBiddingProcess(string _dnsName) public returns(bool transferred) { //get bytes32 representation of the _dnsName bytes32 dnsName = toBytes32(_dnsName); // check for DNSName validity require(isAValidDNSName(dnsName)); // owner should be the one who finalize the bidding-process require(msg.sender == dnsNameDataModelMap[dnsName].nameOwner); // get the highest bid uint bestBidPrice = findTopBidPriceByDNSName(_dnsName); // bidFinalizing tracking Indicator bool isBidFinalized = false; bool fundsTransferredToCurrentOwner = msg.sender.send(bestBidPrice); //transfer bestBidPrice to current-Owner of DNSName //proceed further only if the bestBid-Price fund is transferred to currentOwner if (fundsTransferredToCurrentOwner) { //find the best-Bidder Address address bestBidderAddress = findBestBidderAddressByDNSName(_dnsName); //get bestBidPrice from DNSDataModel (which is the indicativePrice) dnsNameDataModelMap[dnsName].price = bestBidPrice; //transfer ownership by setting bestBidder's address as DNSName-Owner in DNSDataModel dnsNameDataModelMap[dnsName].nameOwner = bestBidderAddress; //get bidRegistry for the dnsName BidRegistry bidRegistry = bidRegistryMap[dnsName]; //deduct funds from the best-Bidder's Address (AKA current owner of the DNSName) bidRegistry.deductFundsFromWinningBidder(bestBidderAddress,bestBidPrice); // as bestBidder has become currentOwner, remove the bestBidder entry from bidRegistry // deactivate bes-Bidder's Bid and update BidState as BID_ACCEPTED require(bidRegistry.updateBidState(bestBidderAddress,DNSStates.BidStates.BID_ACCEPTED,false) == true); isBidFinalized = true; } //emit BidFinalization event emit BidFinalizationEvent(_dnsName, msg.sender, bestBidderAddress, bestBidPrice); return isBidFinalized; } /** * reserve a new DNSName * Name should be non-existent */ function reserveDNSName(string _dnsName) public payable returns(bool isSuccessful) { //get bytes32 representation of the _dnsName bytes32 dnsNameLookupValue = toBytes32(_dnsName); // reserving a DNSName means name shouldn't exist require(isDNSNameReservationAllowed(dnsNameLookupValue)); //get the reservationFee sent by the user uint reservationFees = msg.value; //check if the reservationFees is acceptable require(checkForValidityOfDNSNameBid(reservationFees)); //send reservationFees to the registryOwner bool reservationFeesTransferIndicator = dnsRegistryOwner.send(reservationFees); bool isSuccessfullyReserved = false; if (reservationFeesTransferIndicator) { //add new DNSEntry for _dnsName isSuccessfullyReserved = addNewDNSEntry(dnsNameLookupValue,reservationFees); // create the BidContainer BidRegistry bidRegistry = new BidRegistry(reservationFees); // add reservation as a bid to just-created bidRegistryMap bidRegistryMap[dnsNameLookupValue] = bidRegistry; //emit Reservation-event for new reservation emit ReserveDNSNameEvent(_dnsName, reservationFees, msg.sender, isSuccessfullyReserved); } return isSuccessfullyReserved; } /** * release a pre-owned DNSName * Name should be existent and can be release by nameOwner */ function releaseDNSNameOwnership(string _dnsName) public returns (bool _dnsNameReleasedIndicator) { //get bytes32 representation of the _dnsName bytes32 dnsNameLookupValue = toBytes32(_dnsName); // Name should be existent require(hasDNSOwner(dnsNameLookupValue)); // can be release by nameOwner require(msg.sender == dnsNameDataModelMap[dnsNameLookupValue].nameOwner); // adjust the price to Zero (as name is being released) dnsNameDataModelMap[dnsNameLookupValue].price = 0; //deactivate DNSName so that it can be reserved // this will reset the status and push the DNSName to starting-point of workflow dnsNameDataModelMap[dnsNameLookupValue].active = false; //emit DNSName release-event emit DNSNameOwnershipReleaseEvent(_dnsName); return true; } /** * add new dnsName to DNSDataModel * will be called by reserveDNSName */ function addNewDNSEntry(bytes32 _dnsName, uint _reservationFees) private returns (bool _isSuccessful) { dnsNameDataModelMap[_dnsName].name = _dnsName; dnsNameDataModelMap[_dnsName].nameOwner = msg.sender; dnsNameDataModelMap[_dnsName].price = _reservationFees; dnsNameDataModelMap[_dnsName].active = true; return true; } /** * check if the dnsName Reservation is allowed */ function isDNSNameReservationAllowed(bytes32 _dnsName) internal view returns (bool _isValid) { return !isAValidDNSName(_dnsName); } /** * verify if dnsNameString is valid */ function isAValidDNSName(bytes32 _dnsName) internal view returns (bool _isValid) { DNSDataModel.DNSData storage dnsData = dnsNameDataModelMap[_dnsName]; return dnsData.active; } /** * check the dnsName (byte format) for validity */ function isAValidDNSNameString(string _dnsName) public view returns (bool _isValid) { //get bytes32 representation of the _dnsName bytes32 dnsNameLookupValue = toBytes32(_dnsName); return isAValidDNSName(dnsNameLookupValue); } }
mapping for name to corresponding bidRegistry for name key: dnsNameOwner value: BidRegistry (contains all bids received for the owner)
mapping (bytes32 => BidRegistry) bidRegistryMap;
12,940,606
[ 1, 6770, 364, 508, 358, 4656, 9949, 4243, 364, 508, 498, 30, 6605, 461, 5541, 460, 30, 605, 350, 4243, 261, 12298, 777, 30534, 5079, 364, 326, 3410, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 2874, 261, 3890, 1578, 516, 605, 350, 4243, 13, 9949, 4243, 863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; contract Lottery is VRFConsumerBase { address public owner; address payable[] public players; uint public lotteryID; mapping (uint => address payable) public lotteryHistory; bytes32 internal keyHash; // identifies which chainlink oracle uint internal fee; // fee to get random number uint public randomResult; constructor() VRFConsumerBase( 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, // VRF Coordinator 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 // Link Token Address ) { keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311; fee = 0.1 * 10 ** 18; //0.1 LINK owner = msg.sender; lotteryID = 1; } function getRandomNumber () public returns (bytes32 requestId){ require(LINK.balanceOf(address(this)) >=fee, "Not enough Link in contract"); return requestRandomness(keyHash, fee); } function fulfillRandomness (bytes32 requestId, uint randomness) internal override { randomResult = randomness; payWinner(); } function getWinnerByLottery(uint lotteryidentity) public view returns (address payable) { return lotteryHistory[lotteryidentity]; } function getBalance() public view returns (uint) { return address(this).balance; } function getPlayers() public view returns(address payable[] memory){ return players; } function enter() public payable { require(msg.value > .01 ether); //address of player entering lottery players.push(payable(msg.sender)); } function pickWinner() public onlyOwner { getRandomNumber(); } function payWinner() public { uint index = randomResult % players.length; players[index].transfer(address(this).balance); lotteryHistory[lotteryID] = players[index]; lotteryID++; //reset the state of the contract players = new address payable[](0); } modifier onlyOwner() { require(msg.sender == owner); _; } }
fee to get random number
uint internal fee;
2,492,575
[ 1, 21386, 358, 336, 2744, 1300, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 2713, 14036, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PrizePoolBuilder.sol"; import "../registry/RegistryInterface.sol"; import "../prize-pool/compound/CompoundPrizePoolProxyFactory.sol"; import "../external/compound/CTokenInterface.sol"; /// @title Creates new Compound Prize Pools /* solium-disable security/no-block-members */ contract CompoundPrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; /// @notice The configuration used to initialize the Compound Prize Pool struct CompoundPrizePoolConfig { CTokenInterface cToken; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; CompoundPrizePoolProxyFactory public compoundPrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, CompoundPrizePoolProxyFactory _compoundPrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "CompoundPrizePoolBuilder/reserveRegistry-not-zero"); require(address(_compoundPrizePoolProxyFactory) != address(0), "CompoundPrizePoolBuilder/compound-prize-pool-builder-not-zero"); reserveRegistry = _reserveRegistry; compoundPrizePoolProxyFactory = _compoundPrizePoolProxyFactory; } /// @notice Creates a new Compound Prize Pool with a preconfigured prize strategy. /// @param config The config to use to initialize the Compound Prize Pool /// @return The Compound Prize Pool function createCompoundPrizePool( CompoundPrizePoolConfig calldata config ) external returns (CompoundPrizePool) { CompoundPrizePool prizePool = compoundPrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.cToken ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/PrizePool.sol"; import "../prize-strategy/PeriodicPrizeStrategy.sol"; contract PrizePoolBuilder { using SafeCastUpgradeable for uint256; event PrizePoolCreated ( address indexed creator, address indexed prizePool ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../registry/RegistryInterface.sol"; import "../reserve/ReserveInterface.sol"; import "./YieldSource.sol"; import "../token/TokenListenerInterface.sol"; import "../token/TokenListenerLibrary.sol"; import "../token/ControlledToken.sol"; import "../token/TokenControllerInterface.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./PrizePoolInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens abstract contract PrizePool is PrizePoolInterface, YieldSource, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using ERC165CheckerUpgradeable for address; /// @dev Emitted when an instance is initialized event Initialized( address reserveRegistry, uint256 maxExitFeeMantissa, uint256 maxTimelockDuration ); /// @dev Event emitted when controlled token is added event ControlledTokenAdded( ControlledTokenInterface indexed token ); /// @dev Emitted when reserve is captured. event ReserveFeeCaptured( uint256 amount ); event AwardCaptured( uint256 amount ); /// @dev Event emitted when assets are deposited event Deposited( address indexed operator, address indexed to, address indexed token, uint256 amount, address referrer ); /// @dev Event emitted when timelocked funds are re-deposited event TimelockDeposited( address indexed operator, address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when interest is awarded to a winner event Awarded( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are awarded to a winner event AwardedExternalERC20( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are transferred out event TransferredExternalERC20( address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC721s are awarded to a winner event AwardedExternalERC721( address indexed winner, address indexed token, uint256[] tokenIds ); /// @dev Event emitted when assets are withdrawn instantly event InstantWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 redeemed, uint256 exitFee ); /// @dev Event emitted upon a withdrawal with timelock event TimelockedWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 unlockTimestamp ); event ReserveWithdrawal( address indexed to, uint256 amount ); /// @dev Event emitted when timelocked funds are swept back to a user event TimelockedWithdrawalSwept( address indexed operator, address indexed from, uint256 amount, uint256 redeemed ); /// @dev Event emitted when the Liquidity Cap is set event LiquidityCapSet( uint256 liquidityCap ); /// @dev Event emitted when the Credit plan is set event CreditPlanSet( address token, uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @dev Event emitted when the Prize Strategy is set event PrizeStrategySet( address indexed prizeStrategy ); /// @dev Emitted when credit is minted event CreditMinted( address indexed user, address indexed token, uint256 amount ); /// @dev Emitted when credit is burned event CreditBurned( address indexed user, address indexed token, uint256 amount ); struct CreditPlan { uint128 creditLimitMantissa; uint128 creditRateMantissa; } struct CreditBalance { uint192 balance; uint32 timestamp; bool initialized; } /// @dev Reserve to which reserve fees are sent RegistryInterface public reserveRegistry; /// @dev A linked list of all the controlled tokens MappedSinglyLinkedList.Mapping internal _tokens; /// @dev The Prize Strategy that this Prize Pool is bound to. TokenListenerInterface public prizeStrategy; /// @dev The maximum possible exit fee fraction as a fixed point 18 number. /// For example, if the maxExitFeeMantissa is "0.1 ether", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai uint256 public maxExitFeeMantissa; /// @dev The maximum possible timelock duration for a timelocked withdrawal (in seconds). uint256 public maxTimelockDuration; /// @dev The total funds that are timelocked. uint256 public timelockTotalSupply; /// @dev The total funds that have been allocated to the reserve uint256 public reserveTotalSupply; /// @dev The total amount of funds that the prize pool can hold. uint256 public liquidityCap; /// @dev the The awardable balance uint256 internal _currentAwardBalance; /// @dev The timelocked balances for each user mapping(address => uint256) internal _timelockBalances; /// @dev The unlock timestamps for each user mapping(address => uint256) internal _unlockTimestamps; /// @dev Stores the credit plan for each token. mapping(address => CreditPlan) internal _tokenCreditPlans; /// @dev Stores each users balance of credit per token. mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances; /// @notice Initializes the Prize Pool /// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool. /// @param _maxExitFeeMantissa The maximum exit fee size /// @param _maxTimelockDuration The maximum length of time the withdraw timelock function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration ) public initializer { require(address(_reserveRegistry) != address(0), "PrizePool/reserveRegistry-not-zero"); _tokens.initialize(); for (uint256 i = 0; i < _controlledTokens.length; i++) { _addControlledToken(_controlledTokens[i]); } __Ownable_init(); __ReentrancyGuard_init(); _setLiquidityCap(uint256(-1)); reserveRegistry = _reserveRegistry; maxExitFeeMantissa = _maxExitFeeMantissa; maxTimelockDuration = _maxTimelockDuration; emit Initialized( address(_reserveRegistry), maxExitFeeMantissa, maxTimelockDuration ); } /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external override view returns (address) { return address(_token()); } /// @dev Returns the total underlying balance of all assets. This includes both principal and interest. /// @return The underlying balance of assets function balance() external returns (uint256) { return _balance(); } /// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function canAwardExternal(address _externalToken) external view returns (bool) { return _canAwardExternal(_externalToken); } /// @notice Deposits timelocked tokens for a user back into the Prize Pool as another asset. /// @param to The address receiving the tokens /// @param amount The amount of timelocked assets to re-deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) function timelockDepositTo( address to, uint256 amount, address controlledToken ) external onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, address(0)); _timelockBalances[operator] = _timelockBalances[operator].sub(amount); timelockTotalSupply = timelockTotalSupply.sub(amount); emit TimelockDeposited(operator, to, controlledToken, amount); } /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external override onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, referrer); _token().safeTransferFrom(operator, address(this), amount); _supply(amount); emit Deposited(operator, to, controlledToken, amount, referrer); } /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { (uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); require(exitFee <= maximumExitFee, "PrizePool/exit-fee-exceeds-user-maximum"); // burn the credit _burnCredit(from, controlledToken, burnedCredit); // burn the tickets ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); // redeem the tickets less the fee uint256 amountLessFee = amount.sub(exitFee); uint256 redeemed = _redeem(amountLessFee); _token().safeTransfer(from, redeemed); emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee); return exitFee; } /// @notice Limits the exit fee to the maximum as hard-coded into the contract /// @param withdrawalAmount The amount that is attempting to be withdrawn /// @param exitFee The exit fee to check against the limit /// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned. function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) { uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa); if (exitFee > maxFee) { exitFee = maxFee; } return exitFee; } /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { uint256 blockTime = _currentTime(); (uint256 lockDuration, uint256 burnedCredit) = _calculateTimelockDuration(from, controlledToken, amount); uint256 unlockTimestamp = blockTime.add(lockDuration); _burnCredit(from, controlledToken, burnedCredit); ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); _mintTimelock(from, amount, unlockTimestamp); emit TimelockedWithdrawal(_msgSender(), from, controlledToken, amount, unlockTimestamp); // return the block at which the funds will be available return unlockTimestamp; } /// @notice Adds to a user's timelock balance. It will attempt to sweep before updating the balance. /// Note that this will overwrite the previous unlock timestamp. /// @param user The user whose timelock balance should increase /// @param amount The amount to increase by /// @param timestamp The new unlock timestamp function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } } /// @notice Updates the Prize Strategy when tokens are transferred between holders. /// @param from The address the tokens are being transferred from (0 if minting) /// @param to The address the tokens are being transferred to (0 if burning) /// @param amount The amount of tokens being trasferred function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) { if (from != address(0)) { uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from); // first accrue credit for their old balance uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0); if (from != to) { // if they are sending funds to someone else, we need to limit their accrued credit to their new balance newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance); } _updateCreditBalance(from, msg.sender, newCreditBalance); } if (to != address(0) && to != from) { _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0); } // if we aren't minting if (from != address(0) && address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender); } } /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external override view returns (uint256) { return _currentAwardBalance; } /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external override nonReentrant returns (uint256) { uint256 tokenTotalSupply = _tokenTotalSupply(); // it's possible for the balance to be slightly less due to rounding errors in the underlying yield source uint256 currentBalance = _balance(); uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0; uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0; if (unaccountedPrizeBalance > 0) { uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance); if (reserveFee > 0) { reserveTotalSupply = reserveTotalSupply.add(reserveFee); unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee); emit ReserveFeeCaptured(reserveFee); } _currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance); emit AwardCaptured(unaccountedPrizeBalance); } return _currentAwardBalance; } function withdrawReserve(address to) external override onlyReserve returns (uint256) { uint256 amount = reserveTotalSupply; reserveTotalSupply = 0; uint256 redeemed = _redeem(amount); _token().safeTransfer(address(to), redeemed); emit ReserveWithdrawal(to, amount); return redeemed; } /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external override onlyPrizeStrategy onlyControlledToken(controlledToken) { if (amount == 0) { return; } require(amount <= _currentAwardBalance, "PrizePool/award-exceeds-avail"); _currentAwardBalance = _currentAwardBalance.sub(amount); _mint(to, amount, controlledToken, address(0)); uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount); _accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit); emit Awarded(to, controlledToken, amount); } /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit TransferredExternalERC20(to, externalToken, amount); } } /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit AwardedExternalERC20(to, externalToken, amount); } } function _transferOut( address to, address externalToken, uint256 amount ) internal returns (bool) { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (amount == 0) { return false; } IERC20Upgradeable(externalToken).safeTransfer(to, amount); return true; } /// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired. /// @param to The user who is receiving the tokens /// @param amount The amount of tokens they are receiving /// @param controlledToken The token that is going to be minted /// @param referrer The user who referred the minting function _mint(address to, uint256 amount, address controlledToken, address referrer) internal { if (address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer); } ControlledToken(controlledToken).controllerMint(to, amount); } /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external override onlyPrizeStrategy { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (tokenIds.length == 0) { return; } for (uint256 i = 0; i < tokenIds.length; i++) { IERC721Upgradeable(externalToken).transferFrom(address(this), to, tokenIds[i]); } emit AwardedExternalERC721(to, externalToken, tokenIds); } /// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero. /// @param amount The prize amount /// @return The size of the reserve portion of the prize function calculateReserveFee(uint256 amount) public view returns (uint256) { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); if (address(reserve) == address(0)) { return 0; } uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this)); if (reserveRateMantissa == 0) { return 0; } return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa); } /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external override nonReentrant returns (uint256) { return _sweepTimelockBalances(users); } /// @notice Sweep available timelocked balances to their owners. The full balances will be swept to the owners. /// @param users An array of owner addresses /// @return The total amount of assets swept from the Prize Pool function _sweepTimelockBalances( address[] memory users ) internal returns (uint256) { address operator = _msgSender(); uint256[] memory balances = new uint256[](users.length); uint256 totalWithdrawal; uint256 i; for (i = 0; i < users.length; i++) { address user = users[i]; if (_unlockTimestamps[user] <= _currentTime()) { totalWithdrawal = totalWithdrawal.add(_timelockBalances[user]); balances[i] = _timelockBalances[user]; delete _timelockBalances[user]; } } // if there is nothing to do, just quit if (totalWithdrawal == 0) { return 0; } timelockTotalSupply = timelockTotalSupply.sub(totalWithdrawal); uint256 redeemed = _redeem(totalWithdrawal); IERC20Upgradeable underlyingToken = IERC20Upgradeable(_token()); for (i = 0; i < users.length; i++) { if (balances[i] > 0) { delete _unlockTimestamps[users[i]]; uint256 shareMantissa = FixedPoint.calculateMantissa(balances[i], totalWithdrawal); uint256 transferAmount = FixedPoint.multiplyUintByMantissa(redeemed, shareMantissa); underlyingToken.safeTransfer(users[i], transferAmount); emit TimelockedWithdrawalSwept(operator, users[i], balances[i], transferAmount); } } return totalWithdrawal; } /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external override returns ( uint256 durationSeconds, uint256 burnedCredit ) { return _calculateTimelockDuration(from, controlledToken, amount); } /// @dev Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds /// @return burnedCredit The credit that was burned function _calculateTimelockDuration( address from, address controlledToken, uint256 amount ) internal returns ( uint256 durationSeconds, uint256 burnedCredit ) { (uint256 exitFee, uint256 _burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); uint256 duration = _estimateCreditAccrualTime(controlledToken, amount, exitFee); if (duration > maxTimelockDuration) { duration = maxTimelockDuration; } return (duration, _burnedCredit); } /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external override returns ( uint256 exitFee, uint256 burnedCredit ) { return _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); } /// @dev Calculates the early exit fee for the given amount /// @param amount The amount of collateral to be withdrawn /// @return Exit fee function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) { return _limitExitFee( amount, FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa) ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external override view returns (uint256 durationSeconds) { return _estimateCreditAccrualTime( _controlledToken, _principal, _interest ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function _estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) internal view returns (uint256 durationSeconds) { // interest = credit rate * principal * time // => time = interest / (credit rate * principal) uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa); if (accruedPerSecond == 0) { return 0; } return _interest.div(accruedPerSecond); } /// @notice Burns a users credit. /// @param user The user whose credit should be burned /// @param credit The amount of credit to burn function _burnCredit(address user, address controlledToken, uint256 credit) internal { _tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128(); emit CreditBurned(user, controlledToken, credit); } /// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit. /// @param user The user for whom to accrue credit /// @param controlledToken The controlled token whose balance we are checking /// @param controlledTokenBalance The balance to use for the user /// @param extra Additional credit to be added function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal { _updateCreditBalance( user, controlledToken, _calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra) ); } function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) { uint256 newBalance; CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user]; if (!creditBalance.initialized) { newBalance = 0; } else { uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance); newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra)); } return newBalance; } function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal { uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance; _tokenCreditBalances[controlledToken][user] = CreditBalance({ balance: newBalance.toUint128(), timestamp: _currentTime().toUint32(), initialized: true }); if (oldBalance < newBalance) { emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance)); } else { emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance)); } } /// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The users ticket balance (used to calculate credit limit) /// @param creditBalance The new credit balance to be checked /// @return The users new credit balance. Will not exceed the credit limit. function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) { uint256 creditLimit = FixedPoint.multiplyUintByMantissa( controlledTokenBalance, _tokenCreditPlans[controlledToken].creditLimitMantissa ); if (creditBalance > creditLimit) { creditBalance = creditLimit; } return creditBalance; } /// @notice Calculates the accrued interest for a user /// @param user The user whose credit should be calculated. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The user's current balance of the controlled tokens. /// @return The credit that has accrued since the last credit update. function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) { uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp; if (!_tokenCreditBalances[controlledToken][user].initialized) { return 0; } uint256 deltaTime = _currentTime().sub(userTimestamp); uint256 creditPerSecond = FixedPoint.multiplyUintByMantissa(controlledTokenBalance, _tokenCreditPlans[controlledToken].creditRateMantissa); return deltaTime.mul(creditPerSecond); } /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) { _accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0); return _tokenCreditBalances[controlledToken][user].balance; } /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external override onlyControlledToken(_controlledToken) onlyOwner { _tokenCreditPlans[_controlledToken] = CreditPlan({ creditLimitMantissa: _creditLimitMantissa, creditRateMantissa: _creditRateMantissa }); emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa); } /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external override view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ) { creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa; creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa; } /// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account. /// @param from The user who is withdrawing /// @param controlledToken The token they are withdrawing /// @param amount The amount of funds they are withdrawing /// @return earlyExitFee The additional exit fee that should be charged. /// @return creditBurned The amount of credit that will be burned function _calculateEarlyExitFeeLessBurnedCredit( address from, address controlledToken, uint256 amount ) internal returns ( uint256 earlyExitFee, uint256 creditBurned ) { uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from); require(controlledTokenBalance >= amount, "PrizePool/insuff-funds"); _accrueCredit(from, controlledToken, controlledTokenBalance, 0); /* The credit is used *last*. Always charge the fees up-front. How to calculate: Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit. If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference. */ // Determine available usable credit based on withdraw amount uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount)); uint256 availableCredit; if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) { availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee); } // Determine amount of credit to burn and amount of fees required uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount); creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit; earlyExitFee = totalExitFee.sub(creditBurned); return (earlyExitFee, creditBurned); } /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner { _setLiquidityCap(_liquidityCap); } function _setLiquidityCap(uint256 _liquidityCap) internal { liquidityCap = _liquidityCap; emit LiquidityCapSet(_liquidityCap); } /// @notice Allows the Governor to add Controlled Tokens to the Prize Pool /// @param _controlledToken The address of the Controlled Token to add function addControlledToken(ControlledTokenInterface _controlledToken) external override onlyOwner { _addControlledToken(_controlledToken); } /// @notice Adds a new controlled token /// @param _controlledToken The controlled token to add. Cannot be a duplicate. function _addControlledToken(ControlledTokenInterface _controlledToken) internal { require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch"); _tokens.addAddress(address(_controlledToken)); emit ControlledTokenAdded(_controlledToken); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner { _setPrizeStrategy(_prizeStrategy); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal { require(address(_prizeStrategy) != address(0), "PrizePool/prizeStrategy-not-zero"); require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PrizePool/prizeStrategy-invalid"); prizeStrategy = _prizeStrategy; emit PrizeStrategySet(address(_prizeStrategy)); } /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external override view returns (address[] memory) { return _tokens.addressArray(); } /// @dev Gets the current time as represented by the current block /// @return The timestamp of the current block function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external override view returns (uint256) { return _unlockTimestamps[user]; } /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external override view returns (uint256) { return _timelockBalances[user]; } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external override view returns (uint256) { return _tokenTotalSupply(); } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function _tokenTotalSupply() internal view returns (uint256) { uint256 total = timelockTotalSupply.add(reserveTotalSupply); address currentToken = _tokens.start(); while (currentToken != address(0) && currentToken != _tokens.end()) { total = total.add(IERC20Upgradeable(currentToken).totalSupply()); currentToken = _tokens.next(currentToken); } return total; } /// @dev Checks if the Prize Pool can receive liquidity based on the current cap /// @param _amount The amount of liquidity to be added to the Prize Pool /// @return True if the Prize Pool can receive the specified amount of liquidity function _canAddLiquidity(uint256 _amount) internal view returns (bool) { uint256 tokenTotalSupply = _tokenTotalSupply(); return (tokenTotalSupply.add(_amount) <= liquidityCap); } /// @dev Checks if a specific token is controlled by the Prize Pool /// @param controlledToken The address of the token to check /// @return True if the token is a controlled token, false otherwise function _isControlled(address controlledToken) internal view returns (bool) { return _tokens.contains(controlledToken); } /// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool /// @param controlledToken The address of the token to check modifier onlyControlledToken(address controlledToken) { require(_isControlled(controlledToken), "PrizePool/unknown-token"); _; } /// @dev Function modifier to ensure caller is the prize-strategy modifier onlyPrizeStrategy() { require(_msgSender() == address(prizeStrategy), "PrizePool/only-prizeStrategy"); _; } /// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set) modifier canAddLiquidity(uint256 _amount) { require(_canAddLiquidity(_amount), "PrizePool/exceeds-liquidity-cap"); _; } modifier onlyReserve() { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); require(address(reserve) == msg.sender, "PrizePool/only-reserve"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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); } } } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.8.0; import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol"; /** * @author Brendan Asselstine * @notice Provides basic fixed point math calculations. * * This library calculates integer fractions by scaling values by 1e18 then performing standard integer math. */ library FixedPoint { using OpenZeppelinSafeMath_V3_3_0 for uint256; // The scale to use for fixed point numbers. Same as Ether for simplicity. uint256 internal constant SCALE = 1e18; /** * Calculates a Fixed18 mantissa given the numerator and denominator * * The mantissa = (numerator * 1e18) / denominator * * @param numerator The mantissa numerator * @param denominator The mantissa denominator * @return The mantissa of the fraction */ function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) { uint256 mantissa = numerator.mul(SCALE); mantissa = mantissa.div(denominator); return mantissa; } /** * Multiplies a Fixed18 number by an integer. * * @param b The whole integer to multiply * @param mantissa The Fixed18 number * @return An integer that is the result of multiplying the params. */ function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) { uint256 result = mantissa.mul(b); result = result.div(SCALE); return result; } /** * Divides an integer by a fixed point 18 mantissa * * @param dividend The integer to divide * @param mantissa The fixed point 18 number to serve as the divisor * @return An integer that is the result of dividing an integer by a fixed point 18 mantissa */ function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) { uint256 result = SCALE.mul(dividend); result = result.div(mantissa); return result; } } // SPDX-License-Identifier: MIT // NOTE: Copied from OpenZeppelin Contracts version 3.3.0 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 OpenZeppelinSafeMath_V3_3_0 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface RegistryInterface { function lookup() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface ReserveInterface { function reserveRateMantissa(address prizePool) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title Defines the functions used to interact with a yield source. The Prize Pool inherits this contract. /// @notice Prize Pools subclasses need to implement this interface so that yield can be generated. abstract contract YieldSource { /// @notice Determines whether the passed token can be transferred out as an external award. /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The /// prize strategy should not be allowed to move those tokens. /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal virtual view returns (bool); /// @notice Returns the ERC20 asset token used for deposits. /// @return The ERC20 asset token function _token() internal virtual view returns (IERC20Upgradeable); /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function _balance() internal virtual returns (uint256); /// @notice Supplies asset tokens to the yield source. /// @param mintAmount The amount of asset tokens to be supplied function _supply(uint256 mintAmount) internal virtual; /// @notice Redeems asset tokens from the yield source. /// @param redeemAmount The amount of yield-bearing tokens to be redeemed /// @return The actual amount of tokens that were redeemed. function _redeem(uint256 redeemAmount) internal virtual returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /// @title An interface that allows a contract to listen to token mint, transfer and burn events. interface TokenListenerInterface is IERC165Upgradeable { /// @notice Called when tokens are minted. /// @param to The address of the receiver of the minted tokens. /// @param amount The amount of tokens being minted /// @param controlledToken The address of the token that is being minted /// @param referrer The address that referred the minting. function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external; /// @notice Called when tokens are transferred or burned. /// @param from The address of the sender of the token transfer /// @param to The address of the receiver of the token transfer. Will be the zero address if burning. /// @param amount The amount of tokens transferred /// @param controlledToken The address of the token that was transferred function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external; } pragma solidity ^0.6.12; library TokenListenerLibrary { /* * bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0 * bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957 * * => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7 */ bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "./TokenControllerInterface.sol"; import "./ControlledTokenInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning contract ControlledToken is ERC20Upgradeable, ControlledTokenInterface { /// @notice Interface to the contract responsible for controlling mint/burn TokenControllerInterface public override controller; /// @notice Initializes the Controlled Token with Token Details and the Controller /// @param _name The name of the Token /// @param _symbol The symbol for the Token /// @param _decimals The number of decimals for the Token /// @param _controller Address of the Controller contract for minting & burning function initialize( string memory _name, string memory _symbol, uint8 _decimals, TokenControllerInterface _controller ) public virtual initializer { __ERC20_init(_name, _symbol); controller = _controller; _setupDecimals(_decimals); } /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external virtual override onlyController { _mint(_user, _amount); } /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external virtual override onlyController { _burn(_user, _amount); } /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external virtual override onlyController { if (_operator != _user) { uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, "ControlledToken/exceeds-allowance"); _approve(_user, _operator, decreasedAllowance); } _burn(_user, _amount); } /// @dev Function modifier to ensure that the caller is the controller contract modifier onlyController { require(_msgSender() == address(controller), "ControlledToken/only-controller"); _; } /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { controller.beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Controlled ERC20 Token Interface /// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool /// @dev Defines the spec required to be implemented by a Controlled ERC20 Token interface TokenControllerInterface { /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function beforeTokenTransfer(address from, address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./TokenControllerInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning interface ControlledTokenInterface is IERC20Upgradeable { /// @notice Interface to the contract responsible for controlling mint/burn function controller() external view returns (TokenControllerInterface); /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external; /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external; /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; /// @notice An efficient implementation of a singly linked list of addresses /// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list. library MappedSinglyLinkedList { /// @notice The special value address used to denote the end of the list address public constant SENTINEL = address(0x1); /// @notice The data structure to use for the list. struct Mapping { uint256 count; mapping(address => address) addressMap; } /// @notice Initializes the list. /// @dev It is important that this is called so that the SENTINEL is correctly setup. function initialize(Mapping storage self) internal { require(self.count == 0, "Already init"); self.addressMap[SENTINEL] = SENTINEL; } function start(Mapping storage self) internal view returns (address) { return self.addressMap[SENTINEL]; } function next(Mapping storage self, address current) internal view returns (address) { return self.addressMap[current]; } function end(Mapping storage) internal pure returns (address) { return SENTINEL; } function addAddresses(Mapping storage self, address[] memory addresses) internal { for (uint256 i = 0; i < addresses.length; i++) { addAddress(self, addresses[i]); } } /// @notice Adds an address to the front of the list. /// @param self The Mapping struct that this function is attached to /// @param newAddress The address to shift to the front of the list function addAddress(Mapping storage self, address newAddress) internal { require(newAddress != SENTINEL && newAddress != address(0), "Invalid address"); require(self.addressMap[newAddress] == address(0), "Already added"); self.addressMap[newAddress] = self.addressMap[SENTINEL]; self.addressMap[SENTINEL] = newAddress; self.count = self.count + 1; } /// @notice Removes an address from the list /// @param self The Mapping struct that this function is attached to /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start. /// @param addr The address to remove from the list. function removeAddress(Mapping storage self, address prevAddress, address addr) internal { require(addr != SENTINEL && addr != address(0), "Invalid address"); require(self.addressMap[prevAddress] == addr, "Invalid prevAddress"); self.addressMap[prevAddress] = self.addressMap[addr]; delete self.addressMap[addr]; self.count = self.count - 1; } /// @notice Determines whether the list contains the given address /// @param self The Mapping struct that this function is attached to /// @param addr The address to check /// @return True if the address is contained, false otherwise. function contains(Mapping storage self, address addr) internal view returns (bool) { return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0); } /// @notice Returns an address array of all the addresses in this list /// @dev Contains a for loop, so complexity is O(n) wrt the list size /// @param self The Mapping struct that this function is attached to /// @return An array of all the addresses function addressArray(Mapping storage self) internal view returns (address[] memory) { address[] memory array = new address[](self.count); uint256 count; address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { array[count] = currentAddress; currentAddress = self.addressMap[currentAddress]; count++; } return array; } /// @notice Removes every address from the list /// @param self The Mapping struct that this function is attached to function clearAll(Mapping storage self) internal { address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { address nextAddress = self.addressMap[currentAddress]; delete self.addressMap[currentAddress]; currentAddress = nextAddress; } self.addressMap[SENTINEL] = SENTINEL; self.count = 0; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../token/TokenListenerInterface.sol"; import "../token/ControlledTokenInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens interface PrizePoolInterface { /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external; /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external returns (uint256); /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external returns (uint256); function withdrawReserve(address to) external returns (uint256); /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external view returns (uint256); /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external returns (uint256); /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external; /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external; /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external returns (uint256); /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external returns ( uint256 durationSeconds, uint256 burnedCredit ); /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external returns ( uint256 exitFee, uint256 burnedCredit ); /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external view returns (uint256 durationSeconds); /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external returns (uint256); /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external; /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external; /// @notice Allows the Governor to add Controlled Tokens to the Prize Pool /// @param _controlledToken The address of the Controlled Token to add function addControlledToken(ControlledTokenInterface _controlledToken) external; /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external; /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external view returns (address); /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external view returns (address[] memory); /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external view returns (uint256); /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external view returns (uint256); /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; import "../token/TokenListener.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../token/TokenControllerInterface.sol"; import "../token/ControlledToken.sol"; import "../token/TicketInterface.sol"; import "../prize-pool/PrizePool.sol"; import "../Constants.sol"; import "./PeriodicPrizeStrategyListenerInterface.sol"; import "./PeriodicPrizeStrategyListenerLibrary.sol"; /* solium-disable security/no-block-members */ abstract contract PeriodicPrizeStrategy is Initializable, OwnableUpgradeable, TokenListener { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using AddressUpgradeable for address; using ERC165CheckerUpgradeable for address; uint256 internal constant ETHEREUM_BLOCK_TIME_ESTIMATE_MANTISSA = 13.4 ether; event PrizePoolOpened( address indexed operator, uint256 indexed prizePeriodStartedAt ); event RngRequestFailed(); event PrizePoolAwardStarted( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwardCancelled( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwarded( address indexed operator, uint256 randomNumber ); event RngServiceUpdated( RNGInterface indexed rngService ); event TokenListenerUpdated( TokenListenerInterface indexed tokenListener ); event RngRequestTimeoutSet( uint32 rngRequestTimeout ); event PeriodicPrizeStrategyListenerSet( PeriodicPrizeStrategyListenerInterface indexed periodicPrizeStrategyListener ); event ExternalErc721AwardAdded( IERC721Upgradeable indexed externalErc721, uint256[] tokenIds ); event ExternalErc20AwardAdded( IERC20Upgradeable indexed externalErc20 ); event ExternalErc721AwardRemoved( IERC721Upgradeable indexed externalErc721Award ); event ExternalErc20AwardRemoved( IERC20Upgradeable indexed externalErc20Award ); event Initialized( uint256 prizePeriodStart, uint256 prizePeriodSeconds, PrizePool indexed prizePool, TicketInterface ticket, IERC20Upgradeable sponsorship, RNGInterface rng, IERC20Upgradeable[] externalErc20Awards ); struct RngRequest { uint32 id; uint32 lockBlock; uint32 requestedAt; } // Comptroller TokenListenerInterface public tokenListener; // Contract Interfaces PrizePool public prizePool; TicketInterface public ticket; IERC20Upgradeable public sponsorship; RNGInterface public rng; // Current RNG Request RngRequest internal rngRequest; /// @notice RNG Request Timeout. In fact, this is really a "complete award" timeout. /// If the rng completes the award can still be cancelled. uint32 public rngRequestTimeout; // Prize period uint256 public prizePeriodSeconds; uint256 public prizePeriodStartedAt; // External tokens awarded as part of prize MappedSinglyLinkedList.Mapping internal externalErc20s; MappedSinglyLinkedList.Mapping internal externalErc721s; // External NFT token IDs to be awarded // NFT Address => TokenIds mapping (IERC721Upgradeable => uint256[]) internal externalErc721TokenIds; /// @notice A listener that receives callbacks before certain events PeriodicPrizeStrategyListenerInterface public periodicPrizeStrategyListener; /// @notice Initializes a new strategy /// @param _prizePeriodStart The starting timestamp of the prize period. /// @param _prizePeriodSeconds The duration of the prize period in seconds /// @param _prizePool The prize pool to award /// @param _ticket The ticket to use to draw winners /// @param _sponsorship The sponsorship token /// @param _rng The RNG service to use function initialize ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, IERC20Upgradeable[] memory externalErc20Awards ) public initializer { require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero"); require(address(_prizePool) != address(0), "PeriodicPrizeStrategy/prize-pool-not-zero"); require(address(_ticket) != address(0), "PeriodicPrizeStrategy/ticket-not-zero"); require(address(_sponsorship) != address(0), "PeriodicPrizeStrategy/sponsorship-not-zero"); require(address(_rng) != address(0), "PeriodicPrizeStrategy/rng-not-zero"); prizePool = _prizePool; ticket = _ticket; rng = _rng; sponsorship = _sponsorship; __Ownable_init(); Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); externalErc20s.initialize(); for (uint256 i = 0; i < externalErc20Awards.length; i++) { _addExternalErc20Award(externalErc20Awards[i]); } prizePeriodSeconds = _prizePeriodSeconds; prizePeriodStartedAt = _prizePeriodStart; externalErc721s.initialize(); // 30 min timeout _setRngRequestTimeout(1800); emit Initialized( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, externalErc20Awards ); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } function _distribute(uint256 randomNumber) internal virtual; /// @notice Calculates and returns the currently accrued prize /// @return The current prize size function currentPrize() public view returns (uint256) { return prizePool.awardBalance(); } /// @notice Allows the owner to set the token listener /// @param _tokenListener A contract that implements the token listener interface. function setTokenListener(TokenListenerInterface _tokenListener) external onlyOwner requireAwardNotInProgress { require(address(0) == address(_tokenListener) || address(_tokenListener).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PeriodicPrizeStrategy/token-listener-invalid"); tokenListener = _tokenListener; emit TokenListenerUpdated(tokenListener); } /// @notice Estimates the remaining blocks until the prize given a number of seconds per block /// @param secondsPerBlockMantissa The number of seconds per block to use for the calculation. Should be a fixed point 18 number like Ether. /// @return The estimated number of blocks remaining until the prize can be awarded. function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) { return FixedPoint.divideUintByMantissa( _prizePeriodRemainingSeconds(), secondsPerBlockMantissa ); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function prizePeriodRemainingSeconds() external view returns (uint256) { return _prizePeriodRemainingSeconds(); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function _prizePeriodRemainingSeconds() internal view returns (uint256) { uint256 endAt = _prizePeriodEndAt(); uint256 time = _currentTime(); if (time > endAt) { return 0; } return endAt.sub(time); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function isPrizePeriodOver() external view returns (bool) { return _isPrizePeriodOver(); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function _isPrizePeriodOver() internal view returns (bool) { return _currentTime() >= _prizePeriodEndAt(); } /// @notice Awards collateral as tickets to a user /// @param user The user to whom the tickets are minted /// @param amount The amount of interest to mint as tickets. function _awardTickets(address user, uint256 amount) internal { prizePool.award(user, amount, address(ticket)); } /// @notice Awards all external tokens with non-zero balances to the given user. The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardAllExternalTokens(address winner) internal { _awardExternalErc20s(winner); _awardExternalErc721s(winner); } /// @notice Awards all external ERC20 tokens with non-zero balances to the given user. /// The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardExternalErc20s(address winner) internal { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC20(winner, currentToken, balance); } currentToken = externalErc20s.next(currentToken); } } /// @notice Awards all external ERC721 tokens to the given user. /// The external tokens must be held by the PrizePool contract. /// @dev The list of ERC721s is reset after every award /// @param winner The user to transfer the tokens to function _awardExternalErc721s(address winner) internal { address currentToken = externalErc721s.start(); while (currentToken != address(0) && currentToken != externalErc721s.end()) { uint256 balance = IERC721Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[IERC721Upgradeable(currentToken)]); _removeExternalErc721AwardTokens(IERC721Upgradeable(currentToken)); } currentToken = externalErc721s.next(currentToken); } externalErc721s.clearAll(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function prizePeriodEndAt() external view returns (uint256) { // current prize started at is non-inclusive, so add one return _prizePeriodEndAt(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function _prizePeriodEndAt() internal view returns (uint256) { // current prize started at is non-inclusive, so add one return prizePeriodStartedAt.add(prizePeriodSeconds); } /// @notice Called by the PrizePool for transfers of controlled tokens /// @dev Note that this is only for *transfers*, not mints or burns /// @param controlledToken The type of collateral that is being sent function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool { require(from != to, "PeriodicPrizeStrategy/transfer-to-self"); if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenTransfer(from, to, amount, controlledToken); } } /// @notice Called by the PrizePool when minting controlled tokens /// @param controlledToken The type of collateral that is being minted function beforeTokenMint( address to, uint256 amount, address controlledToken, address referrer ) external override onlyPrizePool { if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenMint(to, amount, controlledToken, referrer); } } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentBlock() internal virtual view returns (uint256) { return block.number; } /// @notice Starts the award process by starting random number request. The prize period must have ended. /// @dev The RNG-Request-Fee is expected to be held within this contract before calling this function function startAward() external requireCanStartAward { (address feeToken, uint256 requestFee) = rng.getRequestFee(); if (feeToken != address(0) && requestFee > 0) { IERC20Upgradeable(feeToken).approve(address(rng), requestFee); } (uint32 requestId, uint32 lockBlock) = rng.requestRandomNumber(); rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; rngRequest.requestedAt = _currentTime().toUint32(); emit PrizePoolAwardStarted(_msgSender(), address(prizePool), requestId, lockBlock); } /// @notice Can be called by anyone to unlock the tickets if the RNG has timed out. function cancelAward() public { require(isRngTimedOut(), "PeriodicPrizeStrategy/rng-not-timedout"); uint32 requestId = rngRequest.id; uint32 lockBlock = rngRequest.lockBlock; delete rngRequest; emit RngRequestFailed(); emit PrizePoolAwardCancelled(msg.sender, address(prizePool), requestId, lockBlock); } /// @notice Completes the award process and awards the winners. The random number must have been requested and is now available. function completeAward() external requireCanCompleteAward { uint256 randomNumber = rng.randomNumber(rngRequest.id); delete rngRequest; _distribute(randomNumber); if (address(periodicPrizeStrategyListener) != address(0)) { periodicPrizeStrategyListener.afterPrizePoolAwarded(randomNumber, prizePeriodStartedAt); } // to avoid clock drift, we should calculate the start time based on the previous period start time. prizePeriodStartedAt = _calculateNextPrizePeriodStartTime(_currentTime()); emit PrizePoolAwarded(_msgSender(), randomNumber); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } /// @notice Allows the owner to set a listener for prize strategy callbacks. /// @param _periodicPrizeStrategyListener The address of the listener contract function setPeriodicPrizeStrategyListener(PeriodicPrizeStrategyListenerInterface _periodicPrizeStrategyListener) external onlyOwner requireAwardNotInProgress { require( address(0) == address(_periodicPrizeStrategyListener) || address(_periodicPrizeStrategyListener).supportsInterface(PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER), "PeriodicPrizeStrategy/prizeStrategyListener-invalid" ); periodicPrizeStrategyListener = _periodicPrizeStrategyListener; emit PeriodicPrizeStrategyListenerSet(_periodicPrizeStrategyListener); } function _calculateNextPrizePeriodStartTime(uint256 currentTime) internal view returns (uint256) { uint256 elapsedPeriods = currentTime.sub(prizePeriodStartedAt).div(prizePeriodSeconds); return prizePeriodStartedAt.add(elapsedPeriods.mul(prizePeriodSeconds)); } /// @notice Calculates when the next prize period will start /// @param currentTime The timestamp to use as the current time /// @return The timestamp at which the next prize period would start function calculateNextPrizePeriodStartTime(uint256 currentTime) external view returns (uint256) { return _calculateNextPrizePeriodStartTime(currentTime); } /// @notice Returns whether an award process can be started /// @return True if an award can be started, false otherwise. function canStartAward() external view returns (bool) { return _isPrizePeriodOver() && !isRngRequested(); } /// @notice Returns whether an award process can be completed /// @return True if an award can be completed, false otherwise. function canCompleteAward() external view returns (bool) { return isRngRequested() && isRngCompleted(); } /// @notice Returns whether a random number has been requested /// @return True if a random number has been requested, false otherwise. function isRngRequested() public view returns (bool) { return rngRequest.id != 0; } /// @notice Returns whether the random number request has completed. /// @return True if a random number request has completed, false otherwise. function isRngCompleted() public view returns (bool) { return rng.isRequestComplete(rngRequest.id); } /// @notice Returns the block number that the current RNG request has been locked to /// @return The block number that the RNG request is locked to function getLastRngLockBlock() external view returns (uint32) { return rngRequest.lockBlock; } /// @notice Returns the current RNG Request ID /// @return The current Request ID function getLastRngRequestId() external view returns (uint32) { return rngRequest.id; } /// @notice Sets the RNG service that the Prize Strategy is connected to /// @param rngService The address of the new RNG service interface function setRngService(RNGInterface rngService) external onlyOwner requireAwardNotInProgress { require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight"); rng = rngService; emit RngServiceUpdated(rngService); } function setRngRequestTimeout(uint32 _rngRequestTimeout) external onlyOwner requireAwardNotInProgress { _setRngRequestTimeout(_rngRequestTimeout); } function _setRngRequestTimeout(uint32 _rngRequestTimeout) internal { require(_rngRequestTimeout > 60, "PeriodicPrizeStrategy/rng-timeout-gt-60-secs"); rngRequestTimeout = _rngRequestTimeout; emit RngRequestTimeoutSet(rngRequestTimeout); } /// @notice Gets the current list of External ERC20 tokens that will be awarded with the current prize /// @return An array of External ERC20 token addresses function getExternalErc20Awards() external view returns (address[] memory) { return externalErc20s.addressArray(); } /// @notice Adds an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// @param _externalErc20 The address of an ERC20 token to be awarded function addExternalErc20Award(IERC20Upgradeable _externalErc20) external onlyOwnerOrListener requireAwardNotInProgress { _addExternalErc20Award(_externalErc20); } function _addExternalErc20Award(IERC20Upgradeable _externalErc20) internal { require(address(_externalErc20).isContract(), "PeriodicPrizeStrategy/erc20-null"); require(prizePool.canAwardExternal(address(_externalErc20)), "PeriodicPrizeStrategy/cannot-award-external"); (bool succeeded, bytes memory returnValue) = address(_externalErc20).staticcall(abi.encodeWithSignature("totalSupply()")); require(succeeded, "PeriodicPrizeStrategy/erc20-invalid"); externalErc20s.addAddress(address(_externalErc20)); emit ExternalErc20AwardAdded(_externalErc20); } function addExternalErc20Awards(IERC20Upgradeable[] calldata _externalErc20s) external onlyOwnerOrListener requireAwardNotInProgress { for (uint256 i = 0; i < _externalErc20s.length; i++) { _addExternalErc20Award(_externalErc20s[i]); } } /// @notice Removes an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc20 The address of an ERC20 token to be removed /// @param _prevExternalErc20 The address of the previous ERC20 token in the `externalErc20s` list. /// If the ERC20 is the first address, then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc20Award(IERC20Upgradeable _externalErc20, IERC20Upgradeable _prevExternalErc20) external onlyOwner requireAwardNotInProgress { externalErc20s.removeAddress(address(_prevExternalErc20), address(_externalErc20)); emit ExternalErc20AwardRemoved(_externalErc20); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721Awards() external view returns (address[] memory) { return externalErc721s.addressArray(); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721AwardTokenIds(IERC721Upgradeable _externalErc721) external view returns (uint256[] memory) { return externalErc721TokenIds[_externalErc721]; } /// @notice Adds an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// NOTE: The NFT must already be owned by the Prize-Pool /// @param _externalErc721 The address of an ERC721 token to be awarded /// @param _tokenIds An array of token IDs of the ERC721 to be awarded function addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener requireAwardNotInProgress { require(prizePool.canAwardExternal(address(_externalErc721)), "PeriodicPrizeStrategy/cannot-award-external"); require(address(_externalErc721).supportsInterface(Constants.ERC165_INTERFACE_ID_ERC721), "PeriodicPrizeStrategy/erc721-invalid"); if (!externalErc721s.contains(address(_externalErc721))) { externalErc721s.addAddress(address(_externalErc721)); } for (uint256 i = 0; i < _tokenIds.length; i++) { _addExternalErc721Award(_externalErc721, _tokenIds[i]); } emit ExternalErc721AwardAdded(_externalErc721, _tokenIds); } function _addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256 _tokenId) internal { require(IERC721Upgradeable(_externalErc721).ownerOf(_tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token"); for (uint256 i = 0; i < externalErc721TokenIds[_externalErc721].length; i++) { if (externalErc721TokenIds[_externalErc721][i] == _tokenId) { revert("PeriodicPrizeStrategy/erc721-duplicate"); } } externalErc721TokenIds[_externalErc721].push(_tokenId); } /// @notice Removes an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc721 The address of an ERC721 token to be removed /// @param _prevExternalErc721 The address of the previous ERC721 token in the list. /// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc721Award( IERC721Upgradeable _externalErc721, IERC721Upgradeable _prevExternalErc721 ) external onlyOwner requireAwardNotInProgress { externalErc721s.removeAddress(address(_prevExternalErc721), address(_externalErc721)); _removeExternalErc721AwardTokens(_externalErc721); } function _removeExternalErc721AwardTokens( IERC721Upgradeable _externalErc721 ) internal { delete externalErc721TokenIds[_externalErc721]; emit ExternalErc721AwardRemoved(_externalErc721); } /// @notice Allows the owner to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address that receives the tokens /// @param externalToken The address of the external asset token being transferred /// @param amount The amount of external assets to be transferred function transferExternalERC20( address to, address externalToken, uint256 amount ) external onlyOwner requireAwardNotInProgress { prizePool.transferExternalERC20(to, externalToken, amount); } function _requireAwardNotInProgress() internal view { uint256 currentBlock = _currentBlock(); require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight"); } function isRngTimedOut() public view returns (bool) { if (rngRequest.requestedAt == 0) { return false; } else { return _currentTime() > uint256(rngRequestTimeout).add(rngRequest.requestedAt); } } modifier onlyOwnerOrListener() { require(_msgSender() == owner() || _msgSender() == address(periodicPrizeStrategyListener), "PeriodicPrizeStrategy/only-owner-or-listener"); _; } modifier requireAwardNotInProgress() { _requireAwardNotInProgress(); _; } modifier requireCanStartAward() { require(_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over"); require(!isRngRequested(), "PeriodicPrizeStrategy/rng-already-requested"); _; } modifier requireCanCompleteAward() { require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested"); require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete"); _; } modifier onlyPrizePool() { require(_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; /// @title Random Number Generator Interface /// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..) interface RNGInterface { /// @notice Emitted when a new request for a random number has been submitted /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param sender The indexed address of the sender of the request event RandomNumberRequested(uint32 indexed requestId, address indexed sender); /// @notice Emitted when an existing request for a random number has been completed /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param randomNumber The random number produced by the 3rd-party service event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber); /// @notice Gets the last request id used by the RNG service /// @return requestId The last request id used in the last request function getLastRequestId() external view returns (uint32 requestId); /// @notice Gets the Fee for making a Request against an RNG service /// @return feeToken The address of the token that is used to pay fees /// @return requestFee The fee required to be paid to make a request function getRequestFee() external view returns (address feeToken, uint256 requestFee); /// @notice Sends a request for a random number to the 3rd-party service /// @dev Some services will complete the request immediately, others may have a time-delay /// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF /// @return requestId The ID of the request used to get the results of the RNG service /// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract /// should "lock" all activity until the result is available via the `requestId` function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock); /// @notice Checks if the request for randomness from the 3rd-party service has completed /// @dev For time-delayed requests, this function is used to check/confirm completion /// @param requestId The ID of the request used to get the results of the RNG service /// @return isCompleted True if the request has completed and a random number is available, false otherwise function isRequestComplete(uint32 requestId) external view returns (bool isCompleted); /// @notice Gets the random number produced by the 3rd-party service /// @param requestId The ID of the request used to get the results of the RNG service /// @return randomNum The random number function randomNumber(uint32 requestId) external returns (uint256 randomNum); } pragma solidity ^0.6.4; import "./TokenListenerInterface.sol"; import "./TokenListenerLibrary.sol"; import "../Constants.sol"; abstract contract TokenListener is TokenListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER ); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC1820RegistryUpgradeable.sol"; library Constants { IERC1820RegistryUpgradeable public constant REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensSender") bytes32 public constant TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); bytes32 public constant ACCEPT_MAGIC = 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd; } // 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: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface TicketInterface { /// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner function draw(uint256 randomNumber) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyListenerInterface is IERC165Upgradeable { function afterPrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; } pragma solidity ^0.6.12; library PeriodicPrizeStrategyListenerLibrary { /* * bytes4(keccak256('afterPrizePoolAwarded(uint256,uint256)')) == 0x575072c6 */ bytes4 public constant ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER = 0x575072c6; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./CompoundPrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract CompoundPrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools CompoundPrizePool public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new CompoundPrizePool(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (CompoundPrizePool) { return CompoundPrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../../external/compound/CTokenInterface.sol"; import "../PrizePool.sol"; /// @title Prize Pool with Compound's cToken /// @notice Manages depositing and withdrawing assets from the Prize Pool contract CompoundPrizePool is PrizePool { using SafeMathUpgradeable for uint256; event CompoundPrizePoolInitialized(address indexed cToken); /// @notice Interface for the Yield-bearing cToken by Compound CTokenInterface public cToken; /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _cToken Address of the Compound cToken interface function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, CTokenInterface _cToken ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); cToken = _cToken; emit CompoundPrizePoolInitialized(address(cToken)); } /// @dev Gets the balance of the underlying assets held by the Yield Service /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service /// @param amount The amount of asset tokens to be supplied function _supply(uint256 amount) internal override { _token().approve(address(cToken), amount); require(cToken.mint(amount) == 0, "CompoundPrizePool/mint-failed"); } /// @dev Checks with the Prize Pool if a specific token type may be awarded as a prize enhancement /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return _externalToken != address(cToken); } /// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying /// asset tokens held in escrow by the Yield Service /// @param amount The amount of underlying tokens to be redeemed /// @return The actual amount of tokens transferred function _redeem(uint256 amount) internal override returns (uint256) { IERC20Upgradeable assetToken = _token(); uint256 before = assetToken.balanceOf(address(this)); require(cToken.redeemUnderlying(amount) == 0, "CompoundPrizePool/redeem-failed"); uint256 diff = assetToken.balanceOf(address(this)).sub(before); return diff; } /// @dev Gets the underlying asset token used by the Yield Service /// @return A reference to the interface of the underling asset token function _token() internal override view returns (IERC20Upgradeable) { return IERC20Upgradeable(cToken.underlying()); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface CTokenInterface is IERC20Upgradeable { function decimals() external view returns (uint8); function totalSupply() external override view returns (uint256); function underlying() external view returns (address); function balanceOfUnderlying(address owner) external returns (uint256); function supplyRatePerBlock() external returns (uint256); function exchangeRateCurrent() external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function balanceOf(address user) external override view returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); } pragma solidity >=0.6.0 <0.7.0; // solium-disable security/no-inline-assembly // solium-disable security/no-low-level-calls contract ProxyFactory { event ProxyCreated(address proxy); function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } emit ProxyCreated(address(proxy)); if(_data.length > 0) { (bool success,) = proxy.call(_data); require(success, "ProxyFactory/constructor-call-failed"); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../token/ControlledTokenProxyFactory.sol"; import "../token/TicketProxyFactory.sol"; /* solium-disable security/no-block-members */ contract ControlledTokenBuilder { event CreatedControlledToken(address indexed token); event CreatedTicket(address indexed token); ControlledTokenProxyFactory public controlledTokenProxyFactory; TicketProxyFactory public ticketProxyFactory; struct ControlledTokenConfig { string name; string symbol; uint8 decimals; TokenControllerInterface controller; } constructor ( ControlledTokenProxyFactory _controlledTokenProxyFactory, TicketProxyFactory _ticketProxyFactory ) public { require(address(_controlledTokenProxyFactory) != address(0), "ControlledTokenBuilder/controlledTokenProxyFactory-not-zero"); require(address(_ticketProxyFactory) != address(0), "ControlledTokenBuilder/ticketProxyFactory-not-zero"); controlledTokenProxyFactory = _controlledTokenProxyFactory; ticketProxyFactory = _ticketProxyFactory; } function createControlledToken( ControlledTokenConfig calldata config ) external returns (ControlledToken) { ControlledToken token = controlledTokenProxyFactory.create(); token.initialize( config.name, config.symbol, config.decimals, config.controller ); emit CreatedControlledToken(address(token)); return token; } function createTicket( ControlledTokenConfig calldata config ) external returns (Ticket) { Ticket token = ticketProxyFactory.create(); token.initialize( config.name, config.symbol, config.decimals, config.controller ); emit CreatedTicket(address(token)); return token; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./ControlledToken.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Controlled ERC20 Token Factory /// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens contract ControlledTokenProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied tokens ControlledToken public instance; /// @notice Initializes the Factory with an instance of the Controlled ERC20 Token constructor () public { instance = new ControlledToken(); } /// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance /// @return A reference to the new proxied Controlled ERC20 Token function create() external returns (ControlledToken) { return ControlledToken(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./Ticket.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Controlled ERC20 Token Factory /// @notice Minimal proxy pattern for creating new Controlled ERC20 Tokens contract TicketProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied tokens Ticket public instance; /// @notice Initializes the Factory with an instance of the Controlled ERC20 Token constructor () public { instance = new Ticket(); } /// @notice Creates a new Controlled ERC20 Token as a proxy of the template instance /// @return A reference to the new proxied Controlled ERC20 Token function create() external returns (Ticket) { return Ticket(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "sortition-sum-tree-factory/contracts/SortitionSumTreeFactory.sol"; import "@pooltogether/uniform-random-number/contracts/UniformRandomNumber.sol"; import "./ControlledToken.sol"; import "./TicketInterface.sol"; contract Ticket is ControlledToken, TicketInterface { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; bytes32 constant private TREE_KEY = keccak256("PoolTogether/Ticket"); uint256 constant private MAX_TREE_LEAVES = 5; // Ticket-weighted odds SortitionSumTreeFactory.SortitionSumTrees internal sortitionSumTrees; /// @notice Initializes the Controlled Token with Token Details and the Controller /// @param _name The name of the Token /// @param _symbol The symbol for the Token /// @param _decimals The number of decimals for the Token /// @param _controller Address of the Controller contract for minting & burning function initialize( string memory _name, string memory _symbol, uint8 _decimals, TokenControllerInterface _controller ) public virtual override initializer { super.initialize(_name, _symbol, _decimals, _controller); sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES); } /// @notice Returns the user's chance of winning. function chanceOf(address user) external view returns (uint256) { return sortitionSumTrees.stakeOf(TREE_KEY, bytes32(uint256(user))); } /// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner function draw(uint256 randomNumber) external view override returns (address) { uint256 bound = totalSupply(); address selected; if (bound == 0) { selected = address(0); } else { uint256 token = UniformRandomNumber.uniform(randomNumber, bound); selected = address(uint256(sortitionSumTrees.draw(TREE_KEY, token))); } return selected; } /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); // optimize: ignore transfers to self if (from == to) { return; } if (from != address(0)) { uint256 fromBalance = balanceOf(from).sub(amount); sortitionSumTrees.set(TREE_KEY, fromBalance, bytes32(uint256(from))); } if (to != address(0)) { uint256 toBalance = balanceOf(to).add(amount); sortitionSumTrees.set(TREE_KEY, toBalance, bytes32(uint256(to))); } } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ pragma solidity ^0.6.0; /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack = new uint[](0); tree.nodes = new uint[](0); tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.pop(); tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start * @return values The values of the returned leaves * @return hasMore Whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.8.0; /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./ControlledTokenBuilder.sol"; import "../prize-strategy/multiple-winners/MultipleWinnersProxyFactory.sol"; /* solium-disable security/no-block-members */ contract MultipleWinnersBuilder { event MultipleWinnersCreated(address indexed prizeStrategy); struct MultipleWinnersConfig { RNGInterface rngService; uint256 prizePeriodStart; uint256 prizePeriodSeconds; string ticketName; string ticketSymbol; string sponsorshipName; string sponsorshipSymbol; uint256 ticketCreditLimitMantissa; uint256 ticketCreditRateMantissa; uint256 numberOfWinners; bool splitExternalErc20Awards; } MultipleWinnersProxyFactory public multipleWinnersProxyFactory; ControlledTokenBuilder public controlledTokenBuilder; constructor ( MultipleWinnersProxyFactory _multipleWinnersProxyFactory, ControlledTokenBuilder _controlledTokenBuilder ) public { require(address(_multipleWinnersProxyFactory) != address(0), "MultipleWinnersBuilder/multipleWinnersProxyFactory-not-zero"); require(address(_controlledTokenBuilder) != address(0), "MultipleWinnersBuilder/token-builder-not-zero"); multipleWinnersProxyFactory = _multipleWinnersProxyFactory; controlledTokenBuilder = _controlledTokenBuilder; } function createMultipleWinners( PrizePool prizePool, MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals, address owner ) external returns (MultipleWinners) { MultipleWinners mw = multipleWinnersProxyFactory.create(); Ticket ticket = _createTicket( prizeStrategyConfig.ticketName, prizeStrategyConfig.ticketSymbol, decimals, prizePool ); ControlledToken sponsorship = _createSponsorship( prizeStrategyConfig.sponsorshipName, prizeStrategyConfig.sponsorshipSymbol, decimals, prizePool ); mw.initializeMultipleWinners( prizeStrategyConfig.prizePeriodStart, prizeStrategyConfig.prizePeriodSeconds, prizePool, ticket, sponsorship, prizeStrategyConfig.rngService, prizeStrategyConfig.numberOfWinners ); if (prizeStrategyConfig.splitExternalErc20Awards) { mw.setSplitExternalErc20Awards(true); } mw.transferOwnership(owner); emit MultipleWinnersCreated(address(mw)); return mw; } function createMultipleWinnersFromExistingPrizeStrategy( PeriodicPrizeStrategy prizeStrategy, uint256 numberOfWinners ) external returns (MultipleWinners) { MultipleWinners mw = multipleWinnersProxyFactory.create(); mw.initializeMultipleWinners( prizeStrategy.prizePeriodStartedAt(), prizeStrategy.prizePeriodSeconds(), prizeStrategy.prizePool(), prizeStrategy.ticket(), prizeStrategy.sponsorship(), prizeStrategy.rng(), numberOfWinners ); mw.transferOwnership(msg.sender); emit MultipleWinnersCreated(address(mw)); return mw; } function _createTicket( string memory name, string memory token, uint8 decimals, PrizePool prizePool ) internal returns (Ticket) { return controlledTokenBuilder.createTicket( ControlledTokenBuilder.ControlledTokenConfig( name, token, decimals, prizePool ) ); } function _createSponsorship( string memory name, string memory token, uint8 decimals, PrizePool prizePool ) internal returns (ControlledToken) { return controlledTokenBuilder.createControlledToken( ControlledTokenBuilder.ControlledTokenConfig( name, token, decimals, prizePool ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./MultipleWinners.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersProxyFactory is ProxyFactory { MultipleWinners public instance; constructor () public { instance = new MultipleWinners(); } function create() external returns (MultipleWinners) { return MultipleWinners(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../PeriodicPrizeStrategy.sol"; contract MultipleWinners is PeriodicPrizeStrategy { uint256 internal __numberOfWinners; bool public splitExternalErc20Awards; event SplitExternalErc20AwardsSet(bool splitExternalErc20Awards); event NumberOfWinnersSet(uint256 numberOfWinners); event NoWinners(); function initializeMultipleWinners ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, uint256 _numberOfWinners ) public initializer { IERC20Upgradeable[] memory _externalErc20Awards; PeriodicPrizeStrategy.initialize( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, _externalErc20Awards ); _setNumberOfWinners(_numberOfWinners); } function setSplitExternalErc20Awards(bool _splitExternalErc20Awards) external onlyOwner requireAwardNotInProgress { splitExternalErc20Awards = _splitExternalErc20Awards; emit SplitExternalErc20AwardsSet(splitExternalErc20Awards); } function setNumberOfWinners(uint256 count) external onlyOwner requireAwardNotInProgress { _setNumberOfWinners(count); } function _setNumberOfWinners(uint256 count) internal { require(count > 0, "MultipleWinners/winners-gte-one"); __numberOfWinners = count; emit NumberOfWinnersSet(count); } function numberOfWinners() external view returns (uint256) { return __numberOfWinners; } function _distribute(uint256 randomNumber) internal override { uint256 prize = prizePool.captureAwardBalance(); // main winner is simply the first that is drawn address mainWinner = ticket.draw(randomNumber); // If drawing yields no winner, then there is no one to pick if (mainWinner == address(0)) { emit NoWinners(); return; } // main winner gets all external ERC721 tokens _awardExternalErc721s(mainWinner); address[] memory winners = new address[](__numberOfWinners); winners[0] = mainWinner; uint256 nextRandom = randomNumber; for (uint256 winnerCount = 1; winnerCount < __numberOfWinners; winnerCount++) { // add some arbitrary numbers to the previous random number to ensure no matches with the UniformRandomNumber lib bytes32 nextRandomHash = keccak256(abi.encodePacked(nextRandom + 499 + winnerCount*521)); nextRandom = uint256(nextRandomHash); winners[winnerCount] = ticket.draw(nextRandom); } // yield prize is split up among all winners uint256 prizeShare = prize.div(winners.length); if (prizeShare > 0) { for (uint i = 0; i < winners.length; i++) { _awardTickets(winners[i], prizeShare); } } if (splitExternalErc20Awards) { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); uint256 split = balance.div(__numberOfWinners); if (split > 0) { for (uint256 i = 0; i < winners.length; i++) { prizePool.awardExternalERC20(winners[i], currentToken, split); } } currentToken = externalErc20s.next(currentToken); } } else { _awardExternalErc20s(mainWinner); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@nomiclabs/buidler/console.sol"; import "./CompoundPrizePoolBuilder.sol"; import "./VaultPrizePoolBuilder.sol"; import "./StakePrizePoolBuilder.sol"; import "./MultipleWinnersBuilder.sol"; contract PoolWithMultipleWinnersBuilder { using SafeCastUpgradeable for uint256; event CompoundPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); event StakePrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); event VaultPrizePoolWithMultipleWinnersCreated(address indexed prizePool, address indexed prizeStrategy); CompoundPrizePoolBuilder public compoundPrizePoolBuilder; VaultPrizePoolBuilder public vaultPrizePoolBuilder; StakePrizePoolBuilder public stakePrizePoolBuilder; MultipleWinnersBuilder public multipleWinnersBuilder; constructor ( CompoundPrizePoolBuilder _compoundPrizePoolBuilder, VaultPrizePoolBuilder _vaultPrizePoolBuilder, StakePrizePoolBuilder _stakePrizePoolBuilder, MultipleWinnersBuilder _multipleWinnersBuilder ) public { require(address(_compoundPrizePoolBuilder) != address(0), "GlobalBuilder/compoundPrizePoolBuilder-not-zero"); require(address(_vaultPrizePoolBuilder) != address(0), "GlobalBuilder/vaultPrizePoolBuilder-not-zero"); require(address(_stakePrizePoolBuilder) != address(0), "GlobalBuilder/stakePrizePoolBuilder-not-zero"); require(address(_multipleWinnersBuilder) != address(0), "GlobalBuilder/multipleWinnersBuilder-not-zero"); compoundPrizePoolBuilder = _compoundPrizePoolBuilder; vaultPrizePoolBuilder = _vaultPrizePoolBuilder; stakePrizePoolBuilder = _stakePrizePoolBuilder; multipleWinnersBuilder = _multipleWinnersBuilder; } function createCompoundMultipleWinners( CompoundPrizePoolBuilder.CompoundPrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (CompoundPrizePool) { CompoundPrizePool prizePool = compoundPrizePoolBuilder.createCompoundPrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit CompoundPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function createStakeMultipleWinners( StakePrizePoolBuilder.StakePrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (StakePrizePool) { StakePrizePool prizePool = stakePrizePoolBuilder.createStakePrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit StakePrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function createVaultMultipleWinners( VaultPrizePoolBuilder.VaultPrizePoolConfig memory prizePoolConfig, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) external returns (yVaultPrizePool) { yVaultPrizePool prizePool = vaultPrizePoolBuilder.createVaultPrizePool(prizePoolConfig); MultipleWinners prizeStrategy = _createMultipleWinnersAndTransferPrizePool(prizePool, prizeStrategyConfig, decimals); emit VaultPrizePoolWithMultipleWinnersCreated(address(prizePool), address(prizeStrategy)); return prizePool; } function _createMultipleWinnersAndTransferPrizePool( PrizePool prizePool, MultipleWinnersBuilder.MultipleWinnersConfig memory prizeStrategyConfig, uint8 decimals ) internal returns (MultipleWinners) { MultipleWinners periodicPrizeStrategy = multipleWinnersBuilder.createMultipleWinners( prizePool, prizeStrategyConfig, decimals, msg.sender ); address ticket = address(periodicPrizeStrategy.ticket()); prizePool.setPrizeStrategy(periodicPrizeStrategy); prizePool.addControlledToken(Ticket(ticket)); prizePool.addControlledToken(ControlledTokenInterface(address(periodicPrizeStrategy.sponsorship()))); prizePool.setCreditPlanOf( ticket, prizeStrategyConfig.ticketCreditRateMantissa.toUint128(), prizeStrategyConfig.ticketCreditLimitMantissa.toUint128() ); prizePool.transferOwnership(msg.sender); return periodicPrizeStrategy; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.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 logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", 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: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../registry/RegistryInterface.sol"; import "./PrizePoolBuilder.sol"; import "../prize-pool/yearn/yVaultPrizePoolProxyFactory.sol"; import "../external/yearn/yVaultInterface.sol"; import "../external/openzeppelin/OpenZeppelinProxyFactoryInterface.sol"; /* solium-disable security/no-block-members */ contract VaultPrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; struct VaultPrizePoolConfig { yVaultInterface vault; uint256 reserveRateMantissa; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; yVaultPrizePoolProxyFactory public vaultPrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, yVaultPrizePoolProxyFactory _vaultPrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "VaultPrizePoolBuilder/reserveRegistry-not-zero"); require(address(_vaultPrizePoolProxyFactory) != address(0), "VaultPrizePoolBuilder/compound-prize-pool-builder-not-zero"); reserveRegistry = _reserveRegistry; vaultPrizePoolProxyFactory = _vaultPrizePoolProxyFactory; } function createVaultPrizePool( VaultPrizePoolConfig calldata config ) external returns (yVaultPrizePool) { yVaultPrizePool prizePool = vaultPrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.vault, config.reserveRateMantissa ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./yVaultPrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title yVault Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new yVault Prize Pools contract yVaultPrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools yVaultPrizePool public instance; /// @notice Initializes the Factory with an instance of the yVault Prize Pool constructor () public { instance = new yVaultPrizePool(); } /// @notice Creates a new yVault Prize Pool as a proxy of the template instance /// @return A reference to the new proxied yVault Prize Pool function create() external returns (yVaultPrizePool) { return yVaultPrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../../external/yearn/yVaultInterface.sol"; import "../PrizePool.sol"; /// @title Prize Pool for yEarn's yVaults contract yVaultPrizePool is PrizePool { using SafeMathUpgradeable for uint256; event yVaultPrizePoolInitialized(address indexed vault); event ReserveRateMantissaSet(uint256 reserveRateMantissa); /// @notice Interface for the yEarn yVault yVaultInterface public vault; /// Amount that is never exposed to the prize uint256 public reserveRateMantissa; /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _vault Address of the yEarn yVaultInterface function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, yVaultInterface _vault, uint256 _reserveRateMantissa ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); vault = _vault; _setReserveRateMantissa(_reserveRateMantissa); emit yVaultPrizePoolInitialized(address(vault)); } function setReserveRateMantissa(uint256 _reserveRateMantissa) external onlyOwner { _setReserveRateMantissa(_reserveRateMantissa); } function _setReserveRateMantissa(uint256 _reserveRateMantissa) internal { require(_reserveRateMantissa < 1 ether, "yVaultPrizePool/reserve-rate-lt-one"); reserveRateMantissa = _reserveRateMantissa; emit ReserveRateMantissaSet(reserveRateMantissa); } /// @dev Gets the balance of the underlying assets held by the Yield Service /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { uint256 total = _sharesToToken(vault.balanceOf(address(this))); uint256 reserve = FixedPoint.multiplyUintByMantissa(total, reserveRateMantissa); return total.sub(reserve); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service function _supply(uint256) internal override { IERC20Upgradeable assetToken = _token(); uint256 total = assetToken.balanceOf(address(this)); assetToken.approve(address(vault), total); vault.deposit(total); } /// @dev Allows a user to supply asset tokens in exchange for yield-bearing tokens /// to be held in escrow by the Yield Service function _supplySpecific(uint256 amount) internal { _token().approve(address(vault), amount); vault.deposit(amount); } /// @dev The external token cannot be yDai or Dai /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return _externalToken != address(vault) && _externalToken != address(vault.token()); } /// @dev Allows a user to redeem yield-bearing tokens in exchange for the underlying /// asset tokens held in escrow by the Yield Service /// @param amount The amount of underlying tokens to be redeemed /// @return The actual amount of tokens transferred function _redeem(uint256 amount) internal override returns (uint256) { IERC20Upgradeable token = _token(); require(_balance() >= amount, "yVaultPrizePool/insuff-liquidity"); // yVault will try to over-withdraw so that amount is always available // we want: amount = X - X*feeRate // amount = X(1 - feeRate) // amount / (1 - feeRate) = X // calculate possible fee uint256 withdrawal; if (reserveRateMantissa > 0) { withdrawal = FixedPoint.divideUintByMantissa(amount, uint256(1e18).sub(reserveRateMantissa)); } else { withdrawal = amount; } uint256 sharesToWithdraw = _tokenToShares(withdrawal); uint256 preBalance = token.balanceOf(address(this)); vault.withdraw(sharesToWithdraw); uint256 postBalance = token.balanceOf(address(this)); uint256 amountWithdrawn = postBalance.sub(preBalance); uint256 amountRedeemable = (amountWithdrawn < amount) ? amountWithdrawn : amount; // Redeposit any asset funds that were removed preemptively for fees if (postBalance > amountRedeemable) { _supplySpecific(postBalance.sub(amountRedeemable)); } return amountRedeemable; } function _tokenToShares(uint256 tokens) internal view returns (uint256) { /** ex. rate = tokens / shares => shares = shares_total * (tokens / tokens total) */ return vault.totalSupply().mul(tokens).div(vault.balance()); } function _sharesToToken(uint256 shares) internal view returns (uint256) { uint256 ts = vault.totalSupply(); if (ts == 0 || shares == 0) { return 0; } return (vault.balance().mul(shares)).div(ts); } /// @dev Gets the underlying asset token used by the Yield Service /// @return A reference to the interface of the underling asset token function _token() internal override view returns (IERC20Upgradeable) { return IERC20Upgradeable(vault.token()); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface yVaultInterface is IERC20Upgradeable { function token() external view returns (IERC20Upgradeable); function balance() external view returns (uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; function getPricePerFullShare() external view returns (uint256); } pragma solidity >=0.6.0 <0.7.0; interface OpenZeppelinProxyFactoryInterface { function deploy(uint256 _salt, address _logic, address _admin, bytes calldata _data) external returns (address); function getDeploymentAddress(uint256 _salt, address _sender) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "./PrizePoolBuilder.sol"; import "../registry/RegistryInterface.sol"; import "../builders/MultipleWinnersBuilder.sol"; import "../prize-pool/stake/StakePrizePoolProxyFactory.sol"; /* solium-disable security/no-block-members */ contract StakePrizePoolBuilder is PrizePoolBuilder { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; struct StakePrizePoolConfig { IERC20Upgradeable token; uint256 maxExitFeeMantissa; uint256 maxTimelockDuration; } RegistryInterface public reserveRegistry; StakePrizePoolProxyFactory public stakePrizePoolProxyFactory; constructor ( RegistryInterface _reserveRegistry, StakePrizePoolProxyFactory _stakePrizePoolProxyFactory ) public { require(address(_reserveRegistry) != address(0), "StakePrizePoolBuilder/reserveRegistry-not-zero"); require(address(_stakePrizePoolProxyFactory) != address(0), "StakePrizePoolBuilder/stake-prize-pool-proxy-factory-not-zero"); reserveRegistry = _reserveRegistry; stakePrizePoolProxyFactory = _stakePrizePoolProxyFactory; } function createStakePrizePool( StakePrizePoolConfig calldata config ) external returns (StakePrizePool) { StakePrizePool prizePool = stakePrizePoolProxyFactory.create(); ControlledTokenInterface[] memory tokens; prizePool.initialize( reserveRegistry, tokens, config.maxExitFeeMantissa, config.maxTimelockDuration, config.token ); prizePool.transferOwnership(msg.sender); emit PrizePoolCreated(msg.sender, address(prizePool)); return prizePool; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./StakePrizePool.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Stake Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new yVault Prize Pools contract StakePrizePoolProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools StakePrizePool public instance; /// @notice Initializes the Factory with an instance of the yVault Prize Pool constructor () public { instance = new StakePrizePool(); } /// @notice Creates a new Stake Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Stake Prize Pool function create() external returns (StakePrizePool) { return StakePrizePool(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../PrizePool.sol"; contract StakePrizePool is PrizePool { IERC20Upgradeable private stakeToken; event StakePrizePoolInitialized(address indexed stakeToken); /// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _maxTimelockDuration The maximum length of time the withdraw timelock could be /// @param _stakeToken Address of the stake token function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, IERC20Upgradeable _stakeToken ) public initializer { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); stakeToken = _stakeToken; emit StakePrizePoolInitialized(address(stakeToken)); } /// @notice Determines whether the passed token can be transferred out as an external award. /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The /// prize strategy should not be allowed to move those tokens. /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal override view returns (bool) { return address(stakeToken) != _externalToken; } /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function _balance() internal override returns (uint256) { return stakeToken.balanceOf(address(this)); } function _token() internal override view returns (IERC20Upgradeable) { return stakeToken; } /// @notice Supplies asset tokens to the yield source. /// @param mintAmount The amount of asset tokens to be supplied function _supply(uint256 mintAmount) internal override { // no-op because nothing else needs to be done } /// @notice Redeems asset tokens from the yield source. /// @param redeemAmount The amount of yield-bearing tokens to be redeemed /// @return The actual amount of tokens that were redeemed. function _redeem(uint256 redeemAmount) internal override returns (uint256) { return redeemAmount; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "../utils/UInt256Array.sol"; import "./ComptrollerStorage.sol"; import "../token/TokenListener.sol"; /// @title The Comptroller disburses rewards to pool users /* solium-disable security/no-block-members */ contract Comptroller is ComptrollerStorage, TokenListener { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using UInt256Array for uint256[]; using ExtendedSafeCast for uint256; using BalanceDrip for BalanceDrip.State; using VolumeDrip for VolumeDrip.State; using BalanceDripManager for BalanceDripManager.State; using VolumeDripManager for VolumeDripManager.State; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; /// @notice Emitted when a balance drip is actived event BalanceDripActivated( address indexed source, address indexed measure, address indexed dripToken, uint256 dripRatePerSecond ); /// @notice Emitted when a balance drip is deactivated event BalanceDripDeactivated( address indexed source, address indexed measure, address indexed dripToken ); /// @notice Emitted when a balance drip rate is updated event BalanceDripRateSet( address indexed source, address indexed measure, address indexed dripToken, uint256 dripRatePerSecond ); /// @notice Emitted when a balance drip drips tokens event BalanceDripDripped( address indexed source, address indexed measure, address indexed dripToken, address user, uint256 amount ); event DripTokenDripped( address indexed dripToken, address indexed user, uint256 amount ); /// @notice Emitted when a volue drip drips tokens event VolumeDripDripped( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, address user, uint256 amount ); /// @notice Emitted when a user claims drip tokens event DripTokenClaimed( address indexed operator, address indexed dripToken, address indexed user, uint256 amount ); /// @notice Emitted when a volume drip is activated event VolumeDripActivated( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint256 periodSeconds, uint256 dripAmount ); event TransferredOut( address indexed token, address indexed to, uint256 amount ); /// @notice Emitted when a new volume drip period has started event VolumeDripPeriodStarted( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint32 period, uint256 dripAmount, uint256 endTime ); /// @notice Emitted when a volume drip period has ended event VolumeDripPeriodEnded( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint32 period, uint256 totalSupply, uint256 drippedTokens ); /// @notice Emitted when a volume drip is updated event VolumeDripSet( address indexed source, address indexed measure, address indexed dripToken, bool isReferral, uint256 periodSeconds, uint256 dripAmount ); /// @notice Emitted when a volume drip is deactivated. event VolumeDripDeactivated( address indexed source, address indexed measure, address indexed dripToken, bool isReferral ); /// @notice Convenience struct used when updating drips struct UpdatePair { address source; address measure; } /// @notice Convenience struct used to retrieve balances after updating drips struct DripTokenBalance { address dripToken; uint256 balance; } /// @notice Initializes a new Comptroller. constructor () public { __Ownable_init(); } function transferOut(address token, address to, uint256 amount) external onlyOwner { IERC20Upgradeable(token).transfer(to, amount); emit TransferredOut(token, to, amount); } /// @notice Activates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param dripRatePerSecond The amount of drip tokens that are awarded each second to the total supply of measure. function activateBalanceDrip(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].activateDrip(measure, dripToken, dripRatePerSecond); emit BalanceDripActivated( source, measure, dripToken, dripRatePerSecond ); } /// @notice Deactivates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address, /// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) external onlyOwner { _deactivateBalanceDrip(source, measure, dripToken, prevDripToken); } /// @notice Deactivates a balance drip. Only callable by the owner. /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @param dripToken The token that is dripped to users. /// @param prevDripToken The previous drip token in the balance drip list. If the dripToken is the first address, /// then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function _deactivateBalanceDrip(address source, address measure, address dripToken, address prevDripToken) internal { balanceDrips[source].deactivateDrip(measure, dripToken, prevDripToken, _currentTime().toUint32(), _availableDripTokenBalance(dripToken)); emit BalanceDripDeactivated(source, measure, dripToken); } /// @notice Gets a list of active balance drip tokens /// @param source The balance drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose balances determines user's share of the drip rate. /// @return An array of active Balance Drip token addresses function getActiveBalanceDripTokens(address source, address measure) external view returns (address[] memory) { return balanceDrips[source].getActiveBalanceDrips(measure); } /// @notice Returns the state of a balance drip. /// @param source The balance drip "source"; i.e. Prize Pool /// @param measure The token that measure's a users share of the drip /// @param dripToken The token that is being dripped to users /// @return dripRatePerSecond The current drip rate of the balance drip. /// @return exchangeRateMantissa The current exchange rate from measure to dripTokens /// @return timestamp The timestamp at which the balance drip was last updated. function getBalanceDrip( address source, address measure, address dripToken ) external view returns ( uint256 dripRatePerSecond, uint128 exchangeRateMantissa, uint32 timestamp ) { BalanceDrip.State storage balanceDrip = balanceDrips[source].getDrip(measure, dripToken); dripRatePerSecond = balanceDrip.dripRatePerSecond; exchangeRateMantissa = balanceDrip.exchangeRateMantissa; timestamp = balanceDrip.timestamp; } /// @notice Sets the drip rate for a balance drip. The drip rate is the number of drip tokens given to the /// entire supply of measure tokens. Only callable by the owner. /// @param source The balance drip "source"; i.e. Prize Pool /// @param measure The token to use to measure a user's share of the drip rate /// @param dripToken The token that is dripped to the user /// @param dripRatePerSecond The new drip rate per second function setBalanceDripRate(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].setDripRate(measure, dripToken, dripRatePerSecond, _currentTime().toUint32(), _availableDripTokenBalance(dripToken)); emit BalanceDripRateSet( source, measure, dripToken, dripRatePerSecond ); } /// @notice Activates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param periodSeconds The period of the volume drip, in seconds /// @param dripAmount The amount of dripTokens disbursed each period. /// @param endTime The time at which the first period ends. function activateVolumeDrip( address source, address measure, address dripToken, bool isReferral, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) external onlyOwner { uint32 period; if (isReferral) { period = referralVolumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime); } else { period = volumeDrips[source].activate(measure, dripToken, periodSeconds, dripAmount, endTime); } emit VolumeDripActivated( source, measure, dripToken, isReferral, periodSeconds, dripAmount ); emit VolumeDripPeriodStarted( source, measure, dripToken, isReferral, period, dripAmount, endTime ); } /// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips. function deactivateVolumeDrip( address source, address measure, address dripToken, bool isReferral, address prevDripToken ) external onlyOwner { _deactivateVolumeDrip(source, measure, dripToken, isReferral, prevDripToken); } /// @notice Deactivates a volume drip. Volume drips distribute tokens to users based on their share of the activity within a period. /// @param source The Prize Pool for which to bind to /// @param measure The Prize Pool controlled token whose volume should be measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is for referrals /// @param prevDripToken The previous drip token in the volume drip list. Is different for referrals vs non-referral volume drips. function _deactivateVolumeDrip( address source, address measure, address dripToken, bool isReferral, address prevDripToken ) internal { if (isReferral) { referralVolumeDrips[source].deactivate(measure, dripToken, prevDripToken); } else { volumeDrips[source].deactivate(measure, dripToken, prevDripToken); } emit VolumeDripDeactivated( source, measure, dripToken, isReferral ); } /// @notice Sets the parameters for the *next* volume drip period. The source, measure, dripToken and isReferral combined /// are used to uniquely identify a volume drip. Only callable by the owner. /// @param source The Prize Pool of the volume drip /// @param measure The token whose volume is being measured /// @param dripToken The token that is being disbursed /// @param isReferral Whether this volume drip is a referral /// @param periodSeconds The length to use for the next period /// @param dripAmount The amount of tokens to drip for the next period function setVolumeDrip( address source, address measure, address dripToken, bool isReferral, uint32 periodSeconds, uint112 dripAmount ) external onlyOwner { if (isReferral) { referralVolumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount); } else { volumeDrips[source].set(measure, dripToken, periodSeconds, dripAmount); } emit VolumeDripSet( source, measure, dripToken, isReferral, periodSeconds, dripAmount ); } function getVolumeDrip( address source, address measure, address dripToken, bool isReferral ) external view returns ( uint256 periodSeconds, uint256 dripAmount, uint256 periodCount ) { VolumeDrip.State memory drip; if (isReferral) { drip = referralVolumeDrips[source].volumeDrips[measure][dripToken]; } else { drip = volumeDrips[source].volumeDrips[measure][dripToken]; } return ( drip.nextPeriodSeconds, drip.nextDripAmount, drip.periodCount ); } /// @notice Gets a list of active volume drip tokens /// @param source The volume drip "source"; i.e. a Prize Pool address. /// @param measure The ERC20 token whose volume determines user's share of the drip rate. /// @param isReferral Whether this volume drip is a referral /// @return An array of active Volume Drip token addresses function getActiveVolumeDripTokens(address source, address measure, bool isReferral) external view returns (address[] memory) { if (isReferral) { return referralVolumeDrips[source].getActiveVolumeDrips(measure); } else { return volumeDrips[source].getActiveVolumeDrips(measure); } } function isVolumeDripActive( address source, address measure, address dripToken, bool isReferral ) external view returns (bool) { if (isReferral) { return referralVolumeDrips[source].isActive(measure, dripToken); } else { return volumeDrips[source].isActive(measure, dripToken); } } function getVolumeDripPeriod( address source, address measure, address dripToken, bool isReferral, uint16 period ) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { VolumeDrip.Period memory periodState; if (isReferral) { periodState = referralVolumeDrips[source].volumeDrips[measure][dripToken].periods[period]; } else { periodState = volumeDrips[source].volumeDrips[measure][dripToken].periods[period]; } return ( periodState.totalSupply, periodState.dripAmount, periodState.endTime ); } /// @notice Returns a users claimable balance of drip tokens. This is the combination of all balance and volume drips. /// @param dripToken The token that is being disbursed /// @param user The user whose balance should be checked. /// @return The claimable balance of the dripToken by the user. function balanceOfDrip(address user, address dripToken) external view returns (uint256) { return dripTokenBalances[dripToken][user]; } /// @notice Claims a drip token on behalf of a user. If the passed amount is less than or equal to the users drip balance, then /// they will be transferred that amount. Otherwise, it fails. /// @param user The user for whom to claim the drip tokens /// @param dripToken The drip token to claim /// @param amount The amount of drip token to claim function claimDrip(address user, address dripToken, uint256 amount) public { address sender = _msgSender(); dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].sub(amount); dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].sub(amount); require(IERC20Upgradeable(dripToken).transfer(user, amount), "Comptroller/claim-transfer-failed"); emit DripTokenClaimed(sender, dripToken, user, amount); } function claimDrips(address user, address[] memory dripTokens) public { for (uint i = 0; i < dripTokens.length; i++) { claimDrip(user, dripTokens[i], dripTokenBalances[dripTokens[i]][user]); } } function updateActiveBalanceDripsForPairs( UpdatePair[] memory pairs ) public { uint256 currentTime = _currentTime(); uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _updateActiveBalanceDrips( balanceDrips[pair.source], pair.source, pair.measure, IERC20Upgradeable(pair.measure).totalSupply(), currentTime ); } } function updateActiveVolumeDripsForPairs( UpdatePair[] memory pairs ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _updateActiveVolumeDrips( volumeDrips[pair.source], pair.source, pair.measure, false ); _updateActiveVolumeDrips( referralVolumeDrips[pair.source], pair.source, pair.measure, true ); } } function mintAndCaptureVolumeDripsForPairs( UpdatePair[] memory pairs, address user, uint256 amount, address[] memory dripTokens ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; _mintAndCaptureForVolumeDrips(pair.source, pair.measure, user, amount, dripTokens); _mintAndCaptureReferralVolumeDrips(pair.source, pair.measure, user, amount, dripTokens); } } function _mintAndCaptureForVolumeDrips( address source, address measure, address user, uint256 amount, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; VolumeDrip.State storage state = volumeDrips[source].volumeDrips[measure][dripToken]; _captureClaimForVolumeDrip(state, source, measure, dripToken, false, user, amount); } } function _mintAndCaptureReferralVolumeDrips( address source, address measure, address user, uint256 amount, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; VolumeDrip.State storage referralState = referralVolumeDrips[source].volumeDrips[measure][dripToken]; _captureClaimForVolumeDrip(referralState, source, measure, dripToken, true, user, amount); } } function _captureClaimForVolumeDrip( VolumeDrip.State storage dripState, address source, address measure, address dripToken, bool isReferral, address user, uint256 amount ) internal { uint256 newUserTokens = dripState.mint( user, amount ); if (newUserTokens > 0) { _addDripBalance(dripToken, user, newUserTokens); emit VolumeDripDripped(source, measure, dripToken, isReferral, user, newUserTokens); } } /// @param pairs The (source, measure) pairs to update. For each pair all of the balance drips, volume drips, and referral volume drips will be updated. /// @param user The user whose drips and balances will be updated. /// @param dripTokens The drip tokens to retrieve claim balances for. function captureClaimsForBalanceDripsForPairs( UpdatePair[] memory pairs, address user, address[] memory dripTokens ) public { uint256 i; for (i = 0; i < pairs.length; i++) { UpdatePair memory pair = pairs[i]; uint256 measureBalance = IERC20Upgradeable(pair.measure).balanceOf(user); _captureClaimsForBalanceDrips(pair.source, pair.measure, user, measureBalance, dripTokens); } } function _captureClaimsForBalanceDrips( address source, address measure, address user, uint256 userMeasureBalance, address[] memory dripTokens ) internal { uint i; for (i = 0; i < dripTokens.length; i++) { address dripToken = dripTokens[i]; BalanceDrip.State storage state = balanceDrips[source].balanceDrips[measure][dripToken]; if (state.exchangeRateMantissa > 0) { _captureClaimForBalanceDrip(state, source, measure, dripToken, user, userMeasureBalance); } } } function _captureClaimForBalanceDrip( BalanceDrip.State storage dripState, address source, address measure, address dripToken, address user, uint256 measureBalance ) internal { uint256 newUserTokens = dripState.captureNewTokensForUser( user, measureBalance ); if (newUserTokens > 0) { _addDripBalance(dripToken, user, newUserTokens); emit BalanceDripDripped(source, measure, dripToken, user, newUserTokens); } } function balanceOfClaims( address user, address[] memory dripTokens ) public view returns (DripTokenBalance[] memory) { DripTokenBalance[] memory balances = new DripTokenBalance[](dripTokens.length); uint256 i; for (i = 0; i < dripTokens.length; i++) { balances[i] = DripTokenBalance({ dripToken: dripTokens[i], balance: dripTokenBalances[dripTokens[i]][user] }); } return balances; } /// @notice Updates the given drips for a user and then claims the given drip tokens. This call will /// poke all of the drips and update the claim balances for the given user. /// @dev This function will be useful to check the *current* claim balances for a user. /// Just need to run this as a constant function to see the latest balances. /// in order to claim the values, this function needs to be run alongside a claimDrip function. /// @param pairs The (source, measure) pairs of drips to update for the given user /// @param user The user for whom to update and claim tokens /// @param dripTokens The drip tokens whose entire balance will be claimed after the update. /// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate. function updateDrips( UpdatePair[] memory pairs, address user, address[] memory dripTokens ) public returns (DripTokenBalance[] memory) { updateActiveBalanceDripsForPairs(pairs); captureClaimsForBalanceDripsForPairs(pairs, user, dripTokens); updateActiveVolumeDripsForPairs(pairs); mintAndCaptureVolumeDripsForPairs(pairs, user, 0, dripTokens); DripTokenBalance[] memory balances = balanceOfClaims(user, dripTokens); return balances; } /// @notice Updates the given drips for a user and then claims the given drip tokens. This call will /// poke all of the drips and update the claim balances for the given user. /// @dev This function will be useful to check the *current* claim balances for a user. /// Just need to run this as a constant function to see the latest balances. /// in order to claim the values, this function needs to be run alongside a claimDrip function. /// @param pairs The (source, measure) pairs of drips to update for the given user /// @param user The user for whom to update and claim tokens /// @param dripTokens The drip tokens whose entire balance will be claimed after the update. /// @return The claimable balance of each of the passed drip tokens for the user. These are the post-update balances, and therefore the most accurate. function updateAndClaimDrips( UpdatePair[] calldata pairs, address user, address[] calldata dripTokens ) external returns (DripTokenBalance[] memory) { DripTokenBalance[] memory balances = updateDrips(pairs, user, dripTokens); claimDrips(user, dripTokens); return balances; } function _activeBalanceDripTokens(address source, address measure) internal view returns (address[] memory) { return balanceDrips[source].activeBalanceDrips[measure].addressArray(); } function _activeVolumeDripTokens(address source, address measure) internal view returns (address[] memory) { return volumeDrips[source].activeVolumeDrips[measure].addressArray(); } function _activeReferralVolumeDripTokens(address source, address measure) internal view returns (address[] memory) { return referralVolumeDrips[source].activeVolumeDrips[measure].addressArray(); } /// @notice Updates the balance drips /// @param source The Prize Pool of the balance drip /// @param manager The BalanceDripManager whose drips should be updated /// @param measure The measure token whose balance is changing /// @param measureTotalSupply The last total supply of the measure tokens /// @param currentTime The current function _updateActiveBalanceDrips( BalanceDripManager.State storage manager, address source, address measure, uint256 measureTotalSupply, uint256 currentTime ) internal { address prevDripToken = manager.activeBalanceDrips[measure].end(); address currentDripToken = manager.activeBalanceDrips[measure].start(); while (currentDripToken != address(0) && currentDripToken != manager.activeBalanceDrips[measure].end()) { BalanceDrip.State storage dripState = manager.balanceDrips[measure][currentDripToken]; uint256 limit = _availableDripTokenBalance(currentDripToken); uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, limit ); // if we've hit the limit, then kill it. bool isDripComplete = newTokens == limit; if (isDripComplete) { _deactivateBalanceDrip(source, measure, currentDripToken, prevDripToken); } prevDripToken = currentDripToken; currentDripToken = manager.activeBalanceDrips[measure].next(currentDripToken); } } /// @notice Records a deposit for a volume drip /// @param source The Prize Pool of the volume drip /// @param manager The VolumeDripManager containing the drips that need to be iterated through. /// @param isReferral Whether the passed manager contains referral volume drip /// @param measure The token that was deposited function _updateActiveVolumeDrips( VolumeDripManager.State storage manager, address source, address measure, bool isReferral ) internal { address prevDripToken = manager.activeVolumeDrips[measure].end(); uint256 currentTime = _currentTime(); address currentDripToken = manager.activeVolumeDrips[measure].start(); while (currentDripToken != address(0) && currentDripToken != manager.activeVolumeDrips[measure].end()) { VolumeDrip.State storage dripState = manager.volumeDrips[measure][currentDripToken]; uint256 limit = _availableDripTokenBalance(currentDripToken); uint32 lastPeriod = dripState.periodCount; uint256 newTokens = dripState.drip( currentTime, limit ); if (lastPeriod != dripState.periodCount) { emit VolumeDripPeriodEnded( source, measure, currentDripToken, isReferral, lastPeriod, dripState.periods[lastPeriod].totalSupply, newTokens ); emit VolumeDripPeriodStarted( source, measure, currentDripToken, isReferral, dripState.periodCount, dripState.periods[dripState.periodCount].dripAmount, dripState.periods[dripState.periodCount].endTime ); } // if we've hit the limit, then kill it. bool isDripComplete = newTokens == limit; if (isDripComplete) { _deactivateVolumeDrip(source, measure, currentDripToken, isReferral, prevDripToken); } prevDripToken = currentDripToken; currentDripToken = manager.activeVolumeDrips[measure].next(currentDripToken); } } function _addDripBalance(address dripToken, address user, uint256 amount) internal returns (uint256) { uint256 amountAvailable = _availableDripTokenBalance(dripToken); uint256 actualAmount = (amount > amountAvailable) ? amountAvailable : amount; dripTokenTotalSupply[dripToken] = dripTokenTotalSupply[dripToken].add(actualAmount); dripTokenBalances[dripToken][user] = dripTokenBalances[dripToken][user].add(actualAmount); emit DripTokenDripped(dripToken, user, actualAmount); return actualAmount; } function _availableDripTokenBalance(address dripToken) internal view returns (uint256) { uint256 comptrollerBalance = IERC20Upgradeable(dripToken).balanceOf(address(this)); uint256 totalClaimable = dripTokenTotalSupply[dripToken]; return (totalClaimable < comptrollerBalance) ? comptrollerBalance.sub(totalClaimable) : 0; } /// @notice Called by a "source" (i.e. Prize Pool) when a user mints new "measure" tokens. /// @param to The user who is minting the tokens /// @param amount The amount of tokens they are minting /// @param measure The measure token they are minting /// @param referrer The user who referred the minting. function beforeTokenMint( address to, uint256 amount, address measure, address referrer ) external override { address source = _msgSender(); uint256 balance = IERC20Upgradeable(measure).balanceOf(to); uint256 totalSupply = IERC20Upgradeable(measure).totalSupply(); address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure); _updateActiveBalanceDrips( balanceDrips[source], source, measure, totalSupply, _currentTime() ); _captureClaimsForBalanceDrips(source, measure, to, balance, balanceDripTokens); address[] memory volumeDripTokens = _activeVolumeDripTokens(source, measure); _updateActiveVolumeDrips( volumeDrips[source], source, measure, false ); _mintAndCaptureForVolumeDrips(source, measure, to, amount, volumeDripTokens); if (referrer != address(0)) { address[] memory referralVolumeDripTokens = _activeReferralVolumeDripTokens(source, measure); _updateActiveVolumeDrips( referralVolumeDrips[source], source, measure, true ); _mintAndCaptureReferralVolumeDrips(source, measure, referrer, amount, referralVolumeDripTokens); } } /// @notice Called by a "source" (i.e. Prize Pool) when tokens change hands or are burned /// @param from The user who is sending the tokens /// @param to The user who is receiving the tokens /// @param measure The measure token they are burning function beforeTokenTransfer( address from, address to, uint256, address measure ) external override { if (from == address(0)) { // ignore minting return; } address source = _msgSender(); uint256 totalSupply = IERC20Upgradeable(measure).totalSupply(); uint256 fromBalance = IERC20Upgradeable(measure).balanceOf(from); address[] memory balanceDripTokens = _activeBalanceDripTokens(source, measure); _updateActiveBalanceDrips( balanceDrips[source], source, measure, totalSupply, _currentTime() ); _captureClaimsForBalanceDrips(source, measure, from, fromBalance, balanceDripTokens); if (to != address(0)) { uint256 toBalance = IERC20Upgradeable(measure).balanceOf(to); _captureClaimsForBalanceDrips(source, measure, to, toBalance, balanceDripTokens); } } /// @notice returns the current time. Allows for override in testing. /// @return The current time (block.timestamp) function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; library UInt256Array { function remove(uint256[] storage self, uint256 index) internal { require(index < self.length, "UInt256Array/unknown-index"); self[index] = self[self.length-1]; delete self[self.length-1]; self.pop(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../drip/BalanceDripManager.sol"; import "../drip/VolumeDripManager.sol"; contract ComptrollerStorage is OwnableUpgradeable { mapping(address => VolumeDripManager.State) internal volumeDrips; mapping(address => VolumeDripManager.State) internal referralVolumeDrips; mapping(address => BalanceDripManager.State) internal balanceDrips; mapping(address => uint256) internal dripTokenTotalSupply; mapping(address => mapping(address => uint256)) internal dripTokenBalances; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./BalanceDrip.sol"; /// @title Manages the lifecycle of a set of Balance Drips. library BalanceDripManager { using SafeMathUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using BalanceDrip for BalanceDrip.State; struct State { mapping(address => MappedSinglyLinkedList.Mapping) activeBalanceDrips; mapping(address => mapping(address => BalanceDrip.State)) balanceDrips; } /// @notice Activates a drip by setting it's state and adding it to the active balance drips list. /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param dripRatePerSecond The amount of the drip token to be dripped per second function activateDrip( State storage self, address measure, address dripToken, uint256 dripRatePerSecond ) internal { require(!self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-active"); if (self.activeBalanceDrips[measure].count == 0) { self.activeBalanceDrips[measure].initialize(); } self.activeBalanceDrips[measure].addAddress(dripToken); self.balanceDrips[measure][dripToken].resetTotalDripped(); self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond; } /// @notice Deactivates an active balance drip. The balance drip is removed from the active balance drips list. /// The drip rate for the balance drip will be set to zero to ensure it's "frozen". /// @param measure The measure token /// @param dripToken The drip token /// @param prevDripToken The previous drip token previous in the list. /// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001 /// @param currentTime The current time function deactivateDrip( State storage self, address measure, address dripToken, address prevDripToken, uint32 currentTime, uint256 maxNewTokens ) internal { self.activeBalanceDrips[measure].removeAddress(prevDripToken, dripToken); self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens); self.balanceDrips[measure][dripToken].dripRatePerSecond = 0; } /// @notice Gets a list of active balance drip tokens /// @param self The BalanceDripManager state /// @param measure The measure token /// @return An array of Balance Drip token addresses function getActiveBalanceDrips(State storage self, address measure) internal view returns (address[] memory) { return self.activeBalanceDrips[measure].addressArray(); } /// @notice Sets the drip rate for an active balance drip. /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param dripRatePerSecond The amount to drip of the token each second /// @param currentTime The current time. function setDripRate( State storage self, address measure, address dripToken, uint256 dripRatePerSecond, uint32 currentTime, uint256 maxNewTokens ) internal { require(self.activeBalanceDrips[measure].contains(dripToken), "BalanceDripManager/drip-not-active"); self.balanceDrips[measure][dripToken].drip(IERC20Upgradeable(measure).totalSupply(), currentTime, maxNewTokens); self.balanceDrips[measure][dripToken].dripRatePerSecond = dripRatePerSecond; } /// @notice Returns whether or not a drip is active for the given measure, dripToken pair /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @return True if there is an active balance drip for the pair, false otherwise function isDripActive(State storage self, address measure, address dripToken) internal view returns (bool) { return self.activeBalanceDrips[measure].contains(dripToken); } /// @notice Returns the BalanceDrip.State for the given measure, dripToken pair /// @param self The BalanceDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @return The BalanceDrip.State for the pair function getDrip(State storage self, address measure, address dripToken) internal view returns (BalanceDrip.State storage) { return self.balanceDrips[measure][dripToken]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "../utils/ExtendedSafeCast.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; /// @title Calculates a users share of a token faucet. /// @notice The tokens are dripped at a "drip rate per second". This is the number of tokens that /// are dripped each second to the entire supply of a "measure" token. A user's share of ownership /// of the measure token corresponds to the share of the drip tokens per second. library BalanceDrip { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using ExtendedSafeCast for uint256; struct UserState { uint128 lastExchangeRateMantissa; } struct State { uint256 dripRatePerSecond; uint112 exchangeRateMantissa; uint112 totalDripped; uint32 timestamp; mapping(address => UserState) userStates; } /// @notice Captures new tokens for a user /// @dev This must be called before changes to the user's balance (i.e. before mint, transfer or burns) /// @param self The balance drip state /// @param user The user to capture tokens for /// @param userMeasureBalance The current balance of the user's measure tokens /// @return The number of new tokens function captureNewTokensForUser( State storage self, address user, uint256 userMeasureBalance ) internal returns (uint128) { return _captureNewTokensForUser( self, user, userMeasureBalance ); } function resetTotalDripped(State storage self) internal { self.totalDripped = 0; } /// @notice Drips new tokens. /// @dev Should be called immediately before a change to the measure token's total supply /// @param self The balance drip state /// @param measureTotalSupply The measure token's last total supply (prior to any change) /// @param timestamp The current time /// @param maxNewTokens Maximum new tokens that can be dripped /// @return The number of new tokens dripped. function drip( State storage self, uint256 measureTotalSupply, uint256 timestamp, uint256 maxNewTokens ) internal returns (uint256) { // this should only run once per block. if (self.timestamp == uint32(timestamp)) { return 0; } uint256 lastTime = self.timestamp == 0 ? timestamp : self.timestamp; uint256 newSeconds = timestamp.sub(lastTime); uint112 exchangeRateMantissa = self.exchangeRateMantissa == 0 ? FixedPoint.SCALE.toUint112() : self.exchangeRateMantissa; uint256 newTokens; if (newSeconds > 0 && self.dripRatePerSecond > 0) { newTokens = newSeconds.mul(self.dripRatePerSecond); if (newTokens > maxNewTokens) { newTokens = maxNewTokens; } uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0; exchangeRateMantissa = uint256(exchangeRateMantissa).add(indexDeltaMantissa).toUint112(); } self.exchangeRateMantissa = exchangeRateMantissa; self.totalDripped = uint256(self.totalDripped).add(newTokens).toUint112(); self.timestamp = timestamp.toUint32(); return newTokens; } function _captureNewTokensForUser( State storage self, address user, uint256 userMeasureBalance ) private returns (uint128) { UserState storage userState = self.userStates[user]; uint256 lastExchangeRateMantissa = userState.lastExchangeRateMantissa; if (lastExchangeRateMantissa == 0) { // if the index is not intialized lastExchangeRateMantissa = FixedPoint.SCALE.toUint112(); } uint256 deltaExchangeRateMantissa = uint256(self.exchangeRateMantissa).sub(lastExchangeRateMantissa); uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128(); self.userStates[user] = UserState({ lastExchangeRateMantissa: self.exchangeRateMantissa }); return newTokens; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; library ExtendedSafeCast { /** * @dev Converts an unsigned uint256 into a unsigned uint112. * * Requirements: * * - input must be less than or equal to maxUint112. */ function toUint112(uint256 value) internal pure returns (uint112) { require(value < 2**112, "SafeCast: value doesn't fit in an uint112"); return uint112(value); } /** * @dev Converts an unsigned uint256 into a unsigned uint96. * * Requirements: * * - input must be less than or equal to maxUint96. */ function toUint96(uint256 value) internal pure returns (uint96) { require(value < 2**96, "SafeCast: value doesn't fit in an uint96"); return uint96(value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./VolumeDrip.sol"; /// @title Manages the active set of Volume Drips. library VolumeDripManager { using SafeMathUpgradeable for uint256; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using VolumeDrip for VolumeDrip.State; struct State { mapping(address => MappedSinglyLinkedList.Mapping) activeVolumeDrips; mapping(address => mapping(address => VolumeDrip.State)) volumeDrips; } /// @notice Activates a volume drip for the given (measure,dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param periodSeconds The period of the volume drip in seconds /// @param dripAmount The amount of tokens to drip each period /// @param endTime The end time to set for the current period. function activate( State storage self, address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) internal returns (uint32) { require(!self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-active"); if (self.activeVolumeDrips[measure].count == 0) { self.activeVolumeDrips[measure].initialize(); } self.activeVolumeDrips[measure].addAddress(dripToken); self.volumeDrips[measure][dripToken].setNewPeriod(periodSeconds, dripAmount, endTime); return self.volumeDrips[measure][dripToken].periodCount; } /// @notice Deactivates the volume drip for the given (measure, dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param prevDripToken The active drip token previous to the passed on in the list. function deactivate( State storage self, address measure, address dripToken, address prevDripToken ) internal { self.activeVolumeDrips[measure].removeAddress(prevDripToken, dripToken); } /// @notice Gets a list of active balance drip tokens /// @param self The BalanceDripManager state /// @param measure The measure token /// @return An array of Balance Drip token addresses function getActiveVolumeDrips(State storage self, address measure) internal view returns (address[] memory) { return self.activeVolumeDrips[measure].addressArray(); } /// @notice Sets the parameters for the next period of an active volume drip /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token /// @param periodSeconds The length in seconds to use for the next period /// @param dripAmount The amount of tokens to be dripped in the next period function set(State storage self, address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) internal { require(self.activeVolumeDrips[measure].contains(dripToken), "VolumeDripManager/drip-not-active"); self.volumeDrips[measure][dripToken].setNextPeriod(periodSeconds, dripAmount); } /// @notice Returns whether or not an active volume drip exists for the given (measure, dripToken) pair /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token function isActive(State storage self, address measure, address dripToken) internal view returns (bool) { return self.activeVolumeDrips[measure].contains(dripToken); } /// @notice Returns the VolumeDrip.State for the given (measure, dripToken) pair. /// @param self The VolumeDripManager state /// @param measure The measure token /// @param dripToken The drip token function getDrip(State storage self, address measure, address dripToken) internal view returns (VolumeDrip.State storage) { return self.volumeDrips[measure][dripToken]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../utils/ExtendedSafeCast.sol"; library VolumeDrip { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using ExtendedSafeCast for uint256; struct Deposit { uint112 balance; uint32 period; } struct Period { uint112 totalSupply; uint112 dripAmount; uint32 endTime; } struct State { mapping(address => Deposit) deposits; mapping(uint32 => Period) periods; uint32 nextPeriodSeconds; uint112 nextDripAmount; uint112 __gap; uint112 totalDripped; uint32 periodCount; } function setNewPeriod( State storage self, uint32 _periodSeconds, uint112 dripAmount, uint32 endTime ) internal minPeriod(_periodSeconds) { self.nextPeriodSeconds = _periodSeconds; self.nextDripAmount = dripAmount; self.totalDripped = 0; self.periodCount = uint256(self.periodCount).add(1).toUint16(); self.periods[self.periodCount] = Period({ totalSupply: 0, dripAmount: dripAmount, endTime: endTime }); } function setNextPeriod( State storage self, uint32 _periodSeconds, uint112 dripAmount ) internal minPeriod(_periodSeconds) { self.nextPeriodSeconds = _periodSeconds; self.nextDripAmount = dripAmount; } function drip( State storage self, uint256 currentTime, uint256 maxNewTokens ) internal returns (uint256) { if (_isPeriodOver(self, currentTime)) { return _completePeriod(self, currentTime, maxNewTokens); } return 0; } function mint( State storage self, address user, uint256 amount ) internal returns (uint256) { if (self.periodCount == 0) { return 0; } uint256 accrued = _lastBalanceAccruedAmount(self, self.deposits[user].period, self.deposits[user].balance); uint32 currentPeriod = self.periodCount; if (accrued > 0) { self.deposits[user] = Deposit({ balance: amount.toUint112(), period: currentPeriod }); } else { self.deposits[user] = Deposit({ balance: uint256(self.deposits[user].balance).add(amount).toUint112(), period: currentPeriod }); } self.periods[currentPeriod].totalSupply = uint256(self.periods[currentPeriod].totalSupply).add(amount).toUint112(); return accrued; } function currentPeriod(State storage self) internal view returns (Period memory) { return self.periods[self.periodCount]; } function _isPeriodOver(State storage self, uint256 currentTime) private view returns (bool) { return currentTime >= self.periods[self.periodCount].endTime; } function _completePeriod( State storage self, uint256 currentTime, uint256 maxNewTokens ) private onlyPeriodOver(self, currentTime) returns (uint256) { // calculate the actual drip amount uint112 dripAmount; // If no one deposited, then don't drip anything if (self.periods[self.periodCount].totalSupply > 0) { dripAmount = self.periods[self.periodCount].dripAmount; } // if the drip amount is not valid, it has to be updated. if (dripAmount > maxNewTokens) { dripAmount = maxNewTokens.toUint112(); self.periods[self.periodCount].dripAmount = dripAmount; } // if we are completing the period far into the future, then we'll have skipped a lot of periods. // Here we set the end time so that it's the next period from *now* uint256 lastEndTime = self.periods[self.periodCount].endTime; uint256 numberOfPeriods = currentTime.sub(lastEndTime).div(self.nextPeriodSeconds).add(1); uint256 endTime = lastEndTime.add(numberOfPeriods.mul(self.nextPeriodSeconds)); self.totalDripped = uint256(self.totalDripped).add(dripAmount).toUint112(); self.periodCount = uint256(self.periodCount).add(1).toUint16(); self.periods[self.periodCount] = Period({ totalSupply: 0, dripAmount: self.nextDripAmount, endTime: endTime.toUint32() }); return dripAmount; } function _lastBalanceAccruedAmount( State storage self, uint32 depositPeriod, uint128 balance ) private view returns (uint256) { uint256 accrued; if (depositPeriod < self.periodCount && self.periods[depositPeriod].totalSupply > 0) { uint256 fractionMantissa = FixedPoint.calculateMantissa(balance, self.periods[depositPeriod].totalSupply); accrued = FixedPoint.multiplyUintByMantissa(self.periods[depositPeriod].dripAmount, fractionMantissa); } return accrued; } modifier onlyPeriodNotOver(State storage self, uint256 _currentTime) { require(!_isPeriodOver(self, _currentTime), "VolumeDrip/period-over"); _; } modifier onlyPeriodOver(State storage self, uint256 _currentTime) { require(_isPeriodOver(self, _currentTime), "VolumeDrip/period-not-over"); _; } modifier minPeriod(uint256 _periodSeconds) { require(_periodSeconds > 0, "VolumeDrip/period-gt-zero"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface DaiInterface is IERC20Upgradeable { // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function transferFrom(address src, address dst, uint wad) external override returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../external/maker/DaiInterface.sol"; import "../prize-pool/PrizePoolInterface.sol"; /// @title Allows users to approve and deposit dai into a prize pool in a single transaction. contract PermitAndDepositDai is OwnableUpgradeable { using SafeERC20Upgradeable for DaiInterface; /// @notice Permits this contract to spend on a users behalf, and deposits into the prize pool. /// @dev The Dai permit params match the Dai#permit function, but it expects the `spender` to be /// the address of this contract. /// @param holder The address spending the tokens /// @param nonce The nonce of the tx. Should be retrieved from the Dai token /// @param expiry The timestamp at which the sig expires /// @param allowed If true, then the spender is approving holder the max allowance. False makes the allowance zero. /// @param v The `v` portion of the signature. /// @param r The `r` portion of the signature. /// @param s The `s` portion of the signature. /// @param prizePool The prize pool to deposit into /// @param to The address that will receive the controlled tokens /// @param amount The amount to deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) /// @param referrer The address that referred the deposit function permitAndDepositTo( // --- Approve by signature --- address dai, address holder, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) external { require(msg.sender == holder, "PermitAndDepositDai/only-signer"); DaiInterface(dai).permit(holder, address(this), nonce, expiry, allowed, v, r, s); _depositTo(dai, holder, prizePool, to, amount, controlledToken, referrer); } /// @notice Deposits into a Prize Pool from the sender. Tokens will be transferred from the sender /// then deposited into the Pool on the sender's behalf. This can be called after permitAndDepositTo is called, /// as this contract will have full approval for a user. /// @param prizePool The prize pool to deposit into /// @param to The address that will receive the controlled tokens /// @param amount The amount to deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) /// @param referrer The address that referred the deposit function depositTo( address dai, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) external { _depositTo(dai, msg.sender, prizePool, to, amount, controlledToken, referrer); } function _depositTo( address dai, address holder, address prizePool, address to, uint256 amount, address controlledToken, address referrer ) internal { DaiInterface(dai).safeTransferFrom(holder, address(this), amount); DaiInterface(dai).approve(address(prizePool), amount); PrizePoolInterface(prizePool).depositTo(to, amount, controlledToken, referrer); } } pragma solidity ^0.6.12; import "./PeriodicPrizeStrategyListenerInterface.sol"; import "./PeriodicPrizeStrategyListenerLibrary.sol"; import "../Constants.sol"; abstract contract PeriodicPrizeStrategyListener is PeriodicPrizeStrategyListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../PeriodicPrizeStrategy.sol"; /* solium-disable security/no-block-members */ contract SingleRandomWinner is PeriodicPrizeStrategy { event NoWinner(); function _distribute(uint256 randomNumber) internal override { uint256 prize = prizePool.captureAwardBalance(); address winner = ticket.draw(randomNumber); if (winner != address(0)) { _awardTickets(winner, prize); _awardAllExternalTokens(winner); } else { emit NoWinner(); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./SingleRandomWinner.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; contract SingleRandomWinnerProxyFactory is ProxyFactory { SingleRandomWinner public instance; constructor () public { instance = new SingleRandomWinner(); } function create() external returns (SingleRandomWinner) { return SingleRandomWinner(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./RegistryInterface.sol"; /// @title Interface that allows a user to draw an address using an index contract Registry is OwnableUpgradeable, RegistryInterface { address private pointer; event Registered(address indexed pointer); constructor () public { __Ownable_init(); } function register(address _pointer) external onlyOwner { pointer = _pointer; emit Registered(pointer); } function lookup() external override view returns (address) { return pointer; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./ReserveInterface.sol"; import "../prize-pool/PrizePoolInterface.sol"; /// @title Interface that allows a user to draw an address using an index contract Reserve is OwnableUpgradeable, ReserveInterface { event ReserveRateMantissaSet(uint256 rateMantissa); uint256 public rateMantissa; constructor () public { __Ownable_init(); } function setRateMantissa( uint256 _rateMantissa ) external onlyOwner { rateMantissa = _rateMantissa; emit ReserveRateMantissaSet(rateMantissa); } function withdrawReserve(address prizePool, address to) external onlyOwner returns (uint256) { return PrizePoolInterface(prizePool).withdrawReserve(to); } function reserveRateMantissa(address) external view override returns (uint256) { return rateMantissa; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/BalanceDrip.sol"; contract BalanceDripExposed { using BalanceDrip for BalanceDrip.State; event DrippedTotalSupply( uint256 newTokens ); event Dripped( address indexed user, uint256 newTokens ); BalanceDrip.State internal dripState; function setDripRate( uint256 dripRatePerSecond ) external { dripState.dripRatePerSecond = dripRatePerSecond; } function drip( uint256 measureTotalSupply, uint256 currentTime, uint256 maxNewTokens ) external returns (uint256) { uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); emit DrippedTotalSupply(newTokens); return newTokens; } function captureNewTokensForUser( address user, uint256 userMeasureBalance ) external returns (uint128) { uint128 newTokens = dripState.captureNewTokensForUser( user, userMeasureBalance ); emit Dripped(user, newTokens); return newTokens; } function dripTwice( uint256 measureTotalSupply, uint256 currentTime, uint256 maxNewTokens ) external returns (uint256) { uint256 newTokens = dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); newTokens = newTokens + dripState.drip( measureTotalSupply, currentTime, maxNewTokens ); emit DrippedTotalSupply(newTokens); return newTokens; } function exchangeRateMantissa() external view returns (uint256) { return dripState.exchangeRateMantissa; } function totalDripped() external view returns (uint256) { return dripState.totalDripped; } function resetTotalDripped() external { dripState.resetTotalDripped(); } } pragma solidity >=0.6.0 <0.7.0; import "../drip/BalanceDripManager.sol"; contract BalanceDripManagerExposed { using BalanceDripManager for BalanceDripManager.State; BalanceDripManager.State dripManager; function activateDrip(address measure, address dripToken, uint256 dripRatePerSecond) external { dripManager.activateDrip(measure, dripToken, dripRatePerSecond); } function deactivateDrip(address measure, address prevDripToken, address dripToken, uint32 currentTime, uint256 maxNewTokens) external { dripManager.deactivateDrip(measure, prevDripToken, dripToken, currentTime, maxNewTokens); } function isDripActive(address measure, address dripToken) external view returns (bool) { return dripManager.isDripActive(measure, dripToken); } function setDripRate(address measure, address dripToken, uint256 dripRatePerSecond, uint32 currentTime, uint256 maxNewTokens) external { dripManager.setDripRate(measure, dripToken, dripRatePerSecond, currentTime, maxNewTokens); } function getActiveBalanceDrips(address measure) external view returns (address[] memory) { return dripManager.getActiveBalanceDrips(measure); } function getDrip( address measure, address dripToken ) external view returns ( uint256 dripRatePerSecond, uint128 exchangeRateMantissa, uint32 timestamp ) { BalanceDrip.State storage dripState = dripManager.getDrip(measure, dripToken); dripRatePerSecond = dripState.dripRatePerSecond; exchangeRateMantissa = dripState.exchangeRateMantissa; timestamp = dripState.timestamp; } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/compound/CompoundPrizePool.sol"; /* solium-disable security/no-block-members */ contract CompoundPrizePoolHarness is CompoundPrizePool { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function setTimelockBalance(uint256 _timelockBalance) external { timelockTotalSupply = _timelockBalance; } function _currentTime() internal override view returns (uint256) { return currentTime; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external returns (uint256) { return _redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "./CompoundPrizePoolHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract CompoundPrizePoolHarnessProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools CompoundPrizePoolHarness public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new CompoundPrizePoolHarness(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (CompoundPrizePoolHarness) { return CompoundPrizePoolHarness(deployMinimal(address(instance), "")); } } pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; import "../comptroller/Comptroller.sol"; /* solium-disable security/no-block-members */ contract ComptrollerHarness is Comptroller { uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } } /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "./ERC20Mintable.sol"; contract CTokenMock is ERC20Upgradeable { mapping(address => uint256) internal ownerTokenAmounts; ERC20Mintable public underlying; uint256 internal __supplyRatePerBlock; constructor ( ERC20Mintable _token, uint256 _supplyRatePerBlock ) public { require(address(_token) != address(0), "token is not defined"); underlying = _token; __supplyRatePerBlock = _supplyRatePerBlock; } function mint(uint256 amount) external returns (uint) { uint256 newCTokens; if (totalSupply() == 0) { newCTokens = amount; } else { // they need to hold the same assets as tokens. // Need to calculate the current exchange rate uint256 fractionOfCredit = FixedPoint.calculateMantissa(amount, underlying.balanceOf(address(this))); newCTokens = FixedPoint.multiplyUintByMantissa(totalSupply(), fractionOfCredit); } _mint(msg.sender, newCTokens); require(underlying.transferFrom(msg.sender, address(this), amount), "could not transfer tokens"); return 0; } function getCash() external view returns (uint) { return underlying.balanceOf(address(this)); } function redeemUnderlying(uint256 requestedAmount) external returns (uint) { uint256 cTokens = cTokenValueOf(requestedAmount); _burn(msg.sender, cTokens); require(underlying.transfer(msg.sender, requestedAmount), "could not transfer tokens"); } function accrue() external { uint256 newTokens = (underlying.balanceOf(address(this)) * 120) / 100; underlying.mint(address(this), newTokens); } function accrueCustom(uint256 amount) external { underlying.mint(address(this), amount); } function burn(uint256 amount) external { underlying.burn(address(this), amount); } function cTokenValueOf(uint256 tokens) public view returns (uint256) { return FixedPoint.divideUintByMantissa(tokens, exchangeRateCurrent()); } function balanceOfUnderlying(address account) public view returns (uint) { return FixedPoint.multiplyUintByMantissa(balanceOf(account), exchangeRateCurrent()); } function exchangeRateCurrent() public view returns (uint256) { if (totalSupply() == 0) { return FixedPoint.SCALE; } else { return FixedPoint.calculateMantissa(underlying.balanceOf(address(this)), totalSupply()); } } function supplyRatePerBlock() external view returns (uint) { return __supplyRatePerBlock; } function setSupplyRateMantissa(uint256 _supplyRatePerBlock) external { __supplyRatePerBlock = _supplyRatePerBlock; } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20Upgradeable { constructor(string memory _name, string memory _symbol) public { __ERC20_init(_name, _symbol); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public returns (bool) { _mint(account, amount); return true; } function burn(address account, uint256 amount) public returns (bool) { _burn(account, amount); return true; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "../external/maker/DaiInterface.sol"; contract Dai is DaiInterface { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (uint256 chainId_) public { string memory version = "1"; _name = "Dai Stablecoin"; _symbol = "DAI"; _decimals = 18; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), chainId_, address(this) ) ); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } mapping (address => uint) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; // --- Approve by signature --- function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external override { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed ) ) ) ); require(holder != address(0), "Dai/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit"); require(expiry == 0 || now <= expiry, "Dai/permit-expired"); require(nonce == nonces[holder]++, "Dai/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; _allowances[holder][spender] = wad; emit Approval(holder, spender, wad); } function mint(address to, uint256 amount) external { _mint(to, amount); } } pragma solidity >=0.6.0 <0.7.0; /* solium-disable security/no-inline-assembly */ contract DoppelgangerWithExec { struct MockCall { bool initialized; bool reverts; bytes returnValue; } mapping(bytes32 => MockCall) mockConfig; fallback() external payable { MockCall storage mockCall = __internal__getMockCall(); if (mockCall.reverts == true) { __internal__mockRevert(); return; } __internal__mockReturn(mockCall.returnValue); } function __waffle__mockReverts(bytes memory data) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: true, returnValue: "" }); } function __waffle__mockReturns(bytes memory data, bytes memory value) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: false, returnValue: value }); } function __waffle__call(address target, bytes calldata data) external returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.call(data); require(succeeded, string(returnValue)); return returnValue; } function __waffle__staticcall(address target, bytes calldata data) external view returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.staticcall(data); require(succeeded, string(returnValue)); return returnValue; } function __internal__getMockCall() view private returns (MockCall storage mockCall) { mockCall = mockConfig[keccak256(msg.data)]; if (mockCall.initialized == true) { // Mock method with specified arguments return mockCall; } mockCall = mockConfig[keccak256(abi.encodePacked(msg.sig))]; if (mockCall.initialized == true) { // Mock method with any arguments return mockCall; } revert("Mock on the method is not initialized"); } function __internal__mockReturn(bytes memory ret) pure private { assembly { return (add(ret, 0x20), mload(ret)) } } function __internal__mockRevert() pure private { revert("Mock revert"); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC1820ImplementerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC777/IERC777RecipientUpgradeable.sol"; import "../Constants.sol"; contract ERC1820ImplementerMock is IERC1820ImplementerUpgradeable, IERC777RecipientUpgradeable { constructor () public { Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function canImplementInterfaceForAddress(bytes32, address) external view virtual override returns(bytes32) { return Constants.ACCEPT_MAGIC; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface for an ERC1820 implementer, as defined in the * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. * Used by contracts that will be registered as implementers in the * {IERC1820Registry}. */ interface IERC1820ImplementerUpgradeable { /** * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract * implements `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } // 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; } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; /** * @dev Extension of {ERC721} for Minting/Burning */ contract ERC721Mintable is ERC721Upgradeable { constructor () public { __ERC721_init("ERC 721", "NFT"); } /** * @dev See {ERC721-_mint}. */ function mint(address to, uint256 tokenId) public { _mint(to, tokenId); } /** * @dev See {ERC721-_burn}. */ function burn(uint256 tokenId) public { _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable 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 => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.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. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, 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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 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 returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * 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 = ownerOf(tokenId); _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(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); _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( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * 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; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // 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 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; } uint256[49] private __gap; } // 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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // 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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } pragma solidity >=0.6.0 <0.7.0; import "../utils/ExtendedSafeCast.sol"; contract ExtendedSafeCastExposed { function toUint112(uint256 value) external pure returns (uint112) { return ExtendedSafeCast.toUint112(value); } function toUint96(uint256 value) external pure returns (uint96) { return ExtendedSafeCast.toUint96(value); } } pragma solidity >=0.6.0 <0.7.0; import "../utils/MappedSinglyLinkedList.sol"; contract MappedSinglyLinkedListExposed { using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; MappedSinglyLinkedList.Mapping list; function initialize() external { list.initialize(); } function addressArray() external view returns (address[] memory) { return list.addressArray(); } function addAddresses(address[] calldata addresses) external { list.addAddresses(addresses); } function addAddress(address newAddress) external { list.addAddress(newAddress); } function removeAddress(address prevAddress, address addr) external { list.removeAddress(prevAddress, addr); } function contains(address addr) external view returns (bool) { return list.contains(addr); } function clearAll() external { list.clearAll(); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/multiple-winners/MultipleWinners.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersHarness is MultipleWinners { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function _currentTime() internal override view returns (uint256) { return currentTime; } function distribute(uint256 randomNumber) external { _distribute(randomNumber); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./MultipleWinnersHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersHarnessProxyFactory is ProxyFactory { MultipleWinnersHarness public instance; constructor () public { instance = new MultipleWinnersHarness(); } function create() external returns (MultipleWinnersHarness) { return MultipleWinnersHarness(deployMinimal(address(instance), "")); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/PeriodicPrizeStrategy.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyDistributorInterface { function distribute(uint256 randomNumber) external; } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/PeriodicPrizeStrategy.sol"; import "./PeriodicPrizeStrategyDistributorInterface.sol"; import "@nomiclabs/buidler/console.sol"; /* solium-disable security/no-block-members */ contract PeriodicPrizeStrategyHarness is PeriodicPrizeStrategy { PeriodicPrizeStrategyDistributorInterface distributor; function setDistributor(PeriodicPrizeStrategyDistributorInterface _distributor) external { distributor = _distributor; } uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } function setRngRequest(uint32 requestId, uint32 lockBlock) external { rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; } function _distribute(uint256 randomNumber) internal override { console.log("random number: ", randomNumber); distributor.distribute(randomNumber); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/PrizePool.sol"; import "./YieldSourceStub.sol"; contract PrizePoolHarness is PrizePool { uint256 public currentTime; YieldSourceStub stubYieldSource; function initializeAll( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration, YieldSourceStub _stubYieldSource ) public { PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa, _maxTimelockDuration ); stubYieldSource = _stubYieldSource; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external { _redeem(redeemAmount); } function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function setTimelockBalance(uint256 _timelockBalance) external { timelockTotalSupply = _timelockBalance; } function _currentTime() internal override view returns (uint256) { return currentTime; } function _canAwardExternal(address _externalToken) internal override view returns (bool) { return stubYieldSource.canAwardExternal(_externalToken); } function _token() internal override view returns (IERC20Upgradeable) { return stubYieldSource.token(); } function _balance() internal override returns (uint256) { return stubYieldSource.balance(); } function _supply(uint256 mintAmount) internal override { return stubYieldSource.supply(mintAmount); } function _redeem(uint256 redeemAmount) internal override returns (uint256) { return stubYieldSource.redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface YieldSourceStub { function canAwardExternal(address _externalToken) external view returns (bool); function token() external view returns (IERC20Upgradeable); function balance() external returns (uint256); function supply(uint256 mintAmount) external; function redeem(uint256 redeemAmount) external returns (uint256); } pragma solidity >=0.6.0 <0.7.0; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; contract RNGServiceMock is RNGInterface { uint256 internal random; address internal feeToken; uint256 internal requestFee; function getLastRequestId() external override view returns (uint32 requestId) { return 1; } function setRequestFee(address _feeToken, uint256 _requestFee) external { feeToken = _feeToken; requestFee = _requestFee; } /// @return _feeToken /// @return _requestFee function getRequestFee() external override view returns (address _feeToken, uint256 _requestFee) { return (feeToken, requestFee); } function setRandomNumber(uint256 _random) external { random = _random; } function requestRandomNumber() external override returns (uint32, uint32) { return (1, 1); } function isRequestComplete(uint32) external override view returns (bool) { return true; } function randomNumber(uint32) external override returns (uint256) { return random; } } pragma solidity >=0.6.0 <0.7.0; import "../prize-strategy/single-random-winner/SingleRandomWinner.sol"; /* solium-disable security/no-block-members */ contract SingleRandomWinnerHarness is SingleRandomWinner { uint256 internal time; function setCurrentTime(uint256 _time) external { time = _time; } function _currentTime() internal override view returns (uint256) { return time; } function setRngRequest(uint32 requestId, uint32 lockBlock) external { rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; } function distribute(uint256 randomNumber) external { _distribute(randomNumber); } } pragma solidity >=0.6.0 <0.7.0; /* solium-disable security/no-block-members */ contract Timestamp { function blockTime() public view returns (uint256) { return block.timestamp; } } pragma solidity >=0.6.0 <0.7.0; import "../utils/UInt256Array.sol"; contract UInt256ArrayExposed { using UInt256Array for uint256[]; uint256[] internal array; constructor (uint256[] memory _array) public { array = new uint256[](_array.length); for (uint256 i = 0; i < _array.length; i++) { array[i] = _array[i]; } } function remove(uint256 index) external { array.remove(index); } function toArray() external view returns (uint256[] memory) { return array; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/VolumeDrip.sol"; contract VolumeDripExposed { using VolumeDrip for VolumeDrip.State; event DripTokensBurned(address user, uint256 amount); event Minted(uint256 amount); event MintedTotalSupply(uint256 amount); VolumeDrip.State state; function setNewPeriod(uint32 periodSeconds, uint112 dripAmount, uint32 endTime) external { state.setNewPeriod(periodSeconds, dripAmount, endTime); } function setNextPeriod(uint32 periodSeconds, uint112 dripAmount) external { state.setNextPeriod(periodSeconds, dripAmount); } function drip(uint256 currentTime, uint256 maxNewTokens) external returns (uint256) { uint256 newTokens = state.drip(currentTime, maxNewTokens); emit MintedTotalSupply(newTokens); return newTokens; } function mint(address user, uint256 amount) external returns (uint256) { uint256 accrued = state.mint(user, amount); emit Minted(accrued); return accrued; } function getDrip() external view returns ( uint32 periodSeconds, uint128 dripAmount ) { periodSeconds = state.nextPeriodSeconds; dripAmount = state.nextDripAmount; } function getPeriod(uint32 period) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { totalSupply = state.periods[period].totalSupply; endTime = state.periods[period].endTime; dripAmount = state.periods[period].dripAmount; } function getDeposit(address user) external view returns ( uint112 balance, uint32 period ) { balance = state.deposits[user].balance; period = state.deposits[user].period; } } pragma solidity >=0.6.0 <0.7.0; import "../drip/VolumeDripManager.sol"; contract VolumeDripManagerExposed { using VolumeDripManager for VolumeDripManager.State; using VolumeDrip for VolumeDrip.State; VolumeDripManager.State manager; function activate( address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount, uint32 endTime ) external { manager.activate(measure, dripToken, periodSeconds, dripAmount, endTime); } function deactivate( address measure, address dripToken, address prevDripToken ) external { manager.deactivate(measure, dripToken, prevDripToken); } function set(address measure, address dripToken, uint32 periodSeconds, uint112 dripAmount) external { manager.set(measure, dripToken, periodSeconds, dripAmount); } function isActive(address measure, address dripToken) external view returns (bool) { return manager.isActive(measure, dripToken); } function getPeriod( address measure, address dripToken, uint32 period ) external view returns ( uint112 totalSupply, uint112 dripAmount, uint32 endTime ) { VolumeDrip.State storage drip = manager.getDrip(measure, dripToken); VolumeDrip.Period memory state = drip.periods[period]; totalSupply = state.totalSupply; dripAmount = state.dripAmount; endTime = state.endTime; } function getActiveVolumeDrips(address measure) external view returns (address[] memory) { return manager.getActiveVolumeDrips(measure); } function getDrip( address measure, address dripToken ) external view returns ( uint32 periodSeconds, uint112 dripAmount ) { VolumeDrip.State storage drip = manager.getDrip(measure, dripToken); dripAmount = drip.nextDripAmount; periodSeconds = drip.nextPeriodSeconds; } } pragma solidity >=0.6.0 <0.7.0; import "../external/yearn/yVaultInterface.sol"; import "./ERC20Mintable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; contract yVaultMock is yVaultInterface, ERC20Upgradeable { ERC20Upgradeable private asset; uint256 public vaultFeeMantissa; constructor (ERC20Mintable _asset) public { asset = _asset; vaultFeeMantissa = 0.05 ether; } function token() external override view returns (IERC20Upgradeable) { return asset; } function balance() public override view returns (uint) { return asset.balanceOf(address(this)); } function removeLiquidity(uint _amount) external { asset.transfer(msg.sender, _amount); } function setVaultFeeMantissa(uint256 _vaultFeeMantissa) external { vaultFeeMantissa = _vaultFeeMantissa; } function deposit(uint _amount) external override { uint _pool = balance(); uint _before = asset.balanceOf(address(this)); asset.transferFrom(msg.sender, address(this), _amount); uint _after = asset.balanceOf(address(this)); uint diff = _after.sub(_before); // Additional check for deflationary assets uint shares = 0; if (totalSupply() == 0) { shares = diff; } else { shares = (diff.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdraw(uint _shares) external override { uint256 sharesFee = FixedPoint.multiplyUintByMantissa(_shares, vaultFeeMantissa); uint256 withdrawal = (balance().mul(_shares.sub(sharesFee))).div(totalSupply()); asset.transfer(msg.sender, withdrawal); _mint(address(this), sharesFee); _burn(msg.sender, _shares); } function getPricePerFullShare() external override view returns (uint) { return balance().mul(1e18).div(totalSupply()); } } pragma solidity >=0.6.0 <0.7.0; import "../prize-pool/yearn/yVaultPrizePool.sol"; contract yVaultPrizePoolHarness is yVaultPrizePool { uint256 public currentTime; function setCurrentTime(uint256 _currentTime) external { currentTime = _currentTime; } function _currentTime() internal override view returns (uint256) { return currentTime; } function supply(uint256 mintAmount) external { _supply(mintAmount); } function redeem(uint256 redeemAmount) external returns (uint256) { return _redeem(redeemAmount); } } pragma solidity >=0.6.0 <0.7.0; import "./yVaultPrizePoolHarness.sol"; import "../external/openzeppelin/ProxyFactory.sol"; /// @title Compound Prize Pool Proxy Factory /// @notice Minimal proxy pattern for creating new Compound Prize Pools contract yVaultPrizePoolHarnessProxyFactory is ProxyFactory { /// @notice Contract template for deploying proxied Prize Pools yVaultPrizePoolHarness public instance; /// @notice Initializes the Factory with an instance of the Compound Prize Pool constructor () public { instance = new yVaultPrizePoolHarness(); } /// @notice Creates a new Compound Prize Pool as a proxy of the template instance /// @return A reference to the new proxied Compound Prize Pool function create() external returns (yVaultPrizePoolHarness) { return yVaultPrizePoolHarness(deployMinimal(address(instance), "")); } }
@notice Sets the drip rate for a balance drip. The drip rate is the number of drip tokens given to the entire supply of measure tokens. Only callable by the owner. @param source The balance drip "source"; i.e. Prize Pool @param measure The token to use to measure a user's share of the drip rate @param dripToken The token that is dripped to the user @param dripRatePerSecond The new drip rate per second
function setBalanceDripRate(address source, address measure, address dripToken, uint256 dripRatePerSecond) external onlyOwner { balanceDrips[source].setDripRate(measure, dripToken, dripRatePerSecond, _currentTime().toUint32(), _availableDripTokenBalance(dripToken)); emit BalanceDripRateSet( source, measure, dripToken, dripRatePerSecond ); }
12,863,603
[ 1, 2785, 326, 302, 21335, 4993, 364, 279, 11013, 302, 21335, 18, 225, 1021, 302, 21335, 4993, 353, 326, 1300, 434, 302, 21335, 2430, 864, 358, 326, 7278, 14467, 434, 6649, 2430, 18, 225, 5098, 4140, 635, 326, 3410, 18, 225, 1084, 1021, 11013, 302, 21335, 315, 3168, 14432, 277, 18, 73, 18, 2301, 554, 8828, 225, 6649, 1021, 1147, 358, 999, 358, 6649, 279, 729, 1807, 7433, 434, 326, 302, 21335, 4993, 225, 302, 21335, 1345, 1021, 1147, 716, 353, 302, 21335, 1845, 358, 326, 729, 225, 302, 21335, 4727, 2173, 8211, 1021, 394, 302, 21335, 4993, 1534, 2205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 13937, 40, 21335, 4727, 12, 2867, 1084, 16, 1758, 6649, 16, 1758, 302, 21335, 1345, 16, 2254, 5034, 302, 21335, 4727, 2173, 8211, 13, 3903, 1338, 5541, 288, 203, 565, 11013, 40, 566, 1121, 63, 3168, 8009, 542, 40, 21335, 4727, 12, 10772, 16, 302, 21335, 1345, 16, 302, 21335, 4727, 2173, 8211, 16, 389, 2972, 950, 7675, 869, 5487, 1578, 9334, 389, 5699, 40, 21335, 1345, 13937, 12, 72, 21335, 1345, 10019, 203, 203, 565, 3626, 30918, 40, 21335, 4727, 694, 12, 203, 1377, 1084, 16, 203, 1377, 6649, 16, 203, 1377, 302, 21335, 1345, 16, 203, 1377, 302, 21335, 4727, 2173, 8211, 203, 565, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x70D802a6aF373F8fF6962a745aB9CeDdEF83BaEc/sources/AI247Token.sol
* @return the address where funds are collected./
function wallet() public view returns (address payable) { return _wallet; }
3,558,782
[ 1, 2463, 326, 1758, 1625, 284, 19156, 854, 12230, 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 ]
[ 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, 9230, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 389, 19177, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /* * Creator: BINO (Binocoin) */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * BINO token smart contract. */ contract BINOToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 100000000 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function BINOToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Binocoin"; string constant public symbol = "BINO"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * To change the approve amount you first have to reduce the addresses` * allowance to zero by calling `approve(_spender, 0)` if it is not * already 0 to mitigate the race condition described here: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
* Maximum allowed number of tokens in circulation. tokenSupply = tokensIActuallyWant (10 ^ decimals)/* Address of the owner of this smart contract./* Frozen account list holder/* Current number of tokens in circulation./* True if tokens transfers are currently frozen, false otherwise./* Create new token smart contract and make msg.sender the owner of this smart contract./
function BINOToken () { owner = msg.sender; }
13,477
[ 1, 13528, 2935, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 1147, 3088, 1283, 273, 2430, 45, 2459, 3452, 59, 970, 225, 261, 2163, 3602, 15105, 13176, 5267, 434, 326, 3410, 434, 333, 13706, 6835, 18, 19, 478, 9808, 2236, 666, 10438, 19, 6562, 1300, 434, 2430, 316, 5886, 1934, 367, 18, 19, 1053, 309, 2430, 29375, 854, 4551, 12810, 16, 629, 3541, 18, 19, 1788, 394, 1147, 13706, 6835, 471, 1221, 1234, 18, 15330, 326, 3410, 434, 333, 13706, 6835, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 18369, 51, 1345, 1832, 288, 203, 565, 3410, 273, 1234, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]